在计算特定属性值时对ID进行分组

时间:2017-03-24 11:01:12

标签: sql-server count group-by where

我想计算表中每个ID的属性月份中值1的出现次数。

以下是我正在使用的内容

    ID.         Months
    1000        1
    1000        1
    1000        2
    1001        2
    1002        3
    1003        1

这就是我想要的

    ID.         Count(Months=1)
    1000        2
    1003        1

1 个答案:

答案 0 :(得分:0)

如果您想将行计算一个月,可以使用WHERE子句进行过滤:

select id,
    count(*) as cnt
from your_table
where month = 1
group by id;

如果你想在一行中获得多个月的计数(它被称为透视),你可以在大多数数据库中使用条件聚合:

select id,
    count(case when month = 1 then 1 end) as cnt_month_1,
    count(case when month = 2 then 1 end) as cnt_month_2,
    count(case when month = 3 then 1 end) as cnt_month_3,
    . . .
from your_table
group by id;

某些数据库为此任务提供PIVOT运算符。为此,您需要指定您正在使用的数据库。