SQL Server - 显示所有可能的值并计算它们

时间:2016-11-07 18:33:01

标签: sql sql-server count

我有下表:

IdSce Year NoIte Value
1     0    1     1 
1     0    2     5
1     0    3     1
1     1    1     2 
1     1    2     3
1     1    3     2
2     0    1     4     
2     0    2     4
2     0    3     1
2     1    1     2 
2     1    2     4
2     1    3     3

我想按IdSce和Year进行分组,并显示每个可能的值并计算每个值出现的时间,如下所示:

IdSce Year Value1  Value2  Value3  Value4  Value5
1     0    2       0       0       0       1 
1     1    0       2       1       0       0
2     0    1       0       0       2       0
2     1    0       1       1       1       0

谢谢!

修改

shawnt00非常接近我想要的,但我希望尽可能动态,这意味着如果我有列的10个不同的值,我将丢失信息我的桌子。因此,如果我有10个不同的值,我想要10个新列(value1,value2,...,value10)

这是我到目前为止所尝试的:

SELECT  IdSce 
        ,Year
        ,SUM(CASE WHEN Value >= 0 and Value < 1 THEN 1 else 0 end) Zero
        ,SUM(CASE WHEN Value >= 1 and Value < 2 THEN 1 else 0 end) One
        ,SUM(CASE WHEN Value >= 2 and Value < 3 THEN 1 else 0 end) Two   
        ,SUM(CASE WHEN Value >= 3 and Value < 4 THEN 1 else 0 end) Three
        ,SUM(CASE WHEN Value >= 4 and Value < 5 THEN 1 else 0 end) Four
        ,SUM(CASE WHEN Value >= 5 THEN 1 else 0 end) FiveMore
        ,SUM(CASE WHEN Value >= 0 THEN 1 else 0 end) Total  
FROM    Table
GROUP BY    IdSce
            ,Year

再次感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

好的,我会的!

select IdSce, "Year"
    count(case when Value = 1 then 1 end) as "1",
    count(case when Value = 2 then 1 end) as "2",
    count(case when Value = 3 then 1 end) as "3",
    count(case when Value = 4 then 1 end) as "4",
    count(case when Value = 5 then 1 end) as "5"
from T
group by IdSce, "Year"

我认为你经常会在“条件聚合”下找到这个。如果您想查看SQL Server,则SQL Server具有使用pivot的专有语法。