0

So far I have this as my SQL Query:

SELECT value, count(value) over () as TOTAL from listofvalues GROUP BY value 

The result look like that:

value|TOTAL 

IS18-0001| 6
IS18-0002| 6
IS18-0003| 6
IS18-0004| 6
IS18-0005| 6
IS18-0006| 6

What I want the result to look like would be more like that:

value|TOTAL 

IS18-0001| 6
IS18-0002|
IS18-0003|
IS18-0004|
IS18-0005|
IS18-0006|

Basically I want to LIMIT the total to 1, but can't seems to find a solution, any idea? Is that even possible?

2
  • Not sure why you want to do this. This seems like something you would not do in sql. Maybe describe the underlying issue? Commented Jan 27, 2018 at 20:05
  • Because at the end I want to use a COPY ... to a CSV, and I want just the total number to appear as 1 value in my CSV file Commented Jan 27, 2018 at 20:19

3 Answers 3

2

You can check for row_number and set other rows to null (or '')

SELECT value, 
case row_number() over () when 1 then count(value) over () else null end as TOTAL 
from listofvalues GROUP BY value 
Sign up to request clarification or add additional context in comments.

Comments

0

It would seem that you don't need the group by, so I would start with:

SELECT value,
       (CASE WHEN row_number() over (order by value) = 1 
             THEN count(*) over ()
        END) as TOTAL
FROM listofvalues ;

The GROUP BY is only needed if you have multiple rows with the same value. If you have duplicates, your query is doing something quite specific -- counting the number of distinct values, while listing each value exactly once. It is not counting the number of rows in the original data.

1 Comment

Hi, thanks for your help it worked, it's the same way as Martin's solution except your the TOTAL number of value is displayed in the first row everytime, that's what I was looking for because then I need to export this query result into a CSV file with a COPY. Thanks.
0

Please try below query. I just added a row number to your query.

Select Value,case when RN=1 then Total else '' END Total 
From(
select value,Cast(Total as varchar) Total,ROW_NUMBER() over (order by value) RN
from(
SELECT value, 
       count(value) over () as TOTAL
 from #listofvalues GROUP BY value 
 )A)B 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.