简体   繁体   English

SQL查询以统计每个不同值的出现

[英]SQL Query to count occurrences of each distinct value

I have a table which contains 2 fields: userid and value . 我有一个包含2个字段的表: useridvalue There can be multiple lines with the same userid . 可以有多个具有相同userid的行 The value column can be one of 5 distinct values. 列可以是5个不同值之一。

I want to output a summary line for each userid , with a count of the times each distinct value appears in the input. 我想为每个userid输出一个摘要行,并计算每个不同出现在输入中的次数。 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 也就是说,摘要行包含以下列: userid值1的 计数,值2的 计数,值3的 计数,值4的 计数和值5的计数

example

1,4 1,4

1,3 1,3

2,1 2,1

3,5 3,5

4,1 4,1

5,2 5,2

output would be 输出将是

1,0,0,1,1,0 1,0,0,1,1,0

2,1,0,0,0,0 2,1,0,0,0,0

3,0,0,0,0,5 3,0,0,0,0,5

4,1,0,0,0,0 4,1,0,0,0,0

5,0,1,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. 您声明输入中的[值]列可以是5个不同值之一。 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. 但是,如果不同值的数量可以随时间增长或不受限制,则将需要使用动态SQL的其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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