简体   繁体   中英

SQL Query to count occurrences of each distinct value

I have a table which contains 2 fields: userid and value . There can be multiple lines with the same userid . The value column can be one of 5 distinct values.

I want to output a summary line for each userid , with a count of the times each distinct value appears in the input. That is, the summary line has the following columns: userid , count of value 1 , count of value 2 , count of value 3 , count of value 4 , and count of value 5

example

1,4

1,3

2,1

3,5

4,1

5,2

output would be

1,0,0,1,1,0

2,1,0,0,0,0

3,0,0,0,0,5

4,1,0,0,0,0

5,0,1,0,0,0

Any suggestions?

Solution

select userid, 
    sum(case value when 1 then [occurs] else 0 end) as countOf1,
    sum(case value when 2 then [occurs] else 0 end) as countOf2,
    sum(case value when 3 then [occurs] else 0 end) as countOf3,
    sum(case value when 4 then [occurs] else 0 end) as countOf4,
    sum(case value when 5 then [occurs] else 0 end) as countOf5
    from
(
    select userid, [value], count(*) as [occurs]
    from inputTable
    group by userid, [value]
) t
group by userid
order by userid

Assumption

I gathered from your question that the same input row values may appear multiple times, although your example data doesn't show that possibility. However, if each distinct row can only appear once, then a significantly simpler/shorter solution is available.

Caveat

You stated that the [value] column in input can be one of 5 distinct values. My solution is based on that "requirement." It includes one line of code for every distinct value. However, if the number of distinct values can grow over time OR is unbounded, then a different approach using dynamic SQL would be required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM