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

Sql server 计算特定属性值时对ID进行分组,sql-server,count,group-by,where,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 如果只想计算一个月

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

这就是我的工作

    ID.         Months
    1000        1
    1000        1
    1000        2
    1001        2
    1002        3
    1003        1
这就是我想要的

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

如果只想计算一个月的行数,可以使用
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
操作符。为此,您需要指定正在使用的数据库。

如果您只想计算一个月的行数,可以使用
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
操作符。为此,您需要指定您正在使用的数据库。

从选项卡t中选择id,sum(Months),其中t.Months='1'按idHi分组,然后欢迎使用Stackoverflow。请阅读以了解如何以正确的方式提问,并了解更多stackoverflow的工作原理。请从选项卡t中选择id,sum(Months),其中t.Months='1'组由idHi显示,欢迎使用stackoverflow。请阅读以了解如何以正确的方式提问,并了解更多stackoverflow的工作原理。