Sql查询分组(使用where where condition获取计数)

时间:2018-04-10 15:21:03

标签: sql sql-server group-by

坚持分组。

Col1      Col2
----------------
1         1
1         2
2         1
3         3
4         2
5         4
2         3

我想要Col2的数量使得Col2值为1: 预期的输出是:

Col1      Count(Col2)
---------------------
1         1
2         1
3         0
4         0
5         0

先谢谢。

2 个答案:

答案 0 :(得分:0)

;with
d as (
select * from (values 
(1,         1),
(1,         2),
(2,         1),
(3,         3),
(4,         2),
(5,         4),
(2,         3)) x (Col1, Col2)
)
select distinct d1.Col1, isnull(cnt, 0) cnt
from d d1
left join (
    select Col1, COUNT(Col2) cnt
    from d d1
    where Col2=1
    group by Col1, col2
) d2 on d1.Col1 = d2.Col1 
order by 1,2

输出:

Col1    Cnt
1       1
2       1
3       0
4       0
5       0

答案 1 :(得分:-1)

您可以使用条件聚合:

select col1, sum(case when col2 = 1 then 1 else 0 end)
from t
group by col1;