如何根据不同条件添加group by子句?

时间:2019-06-18 18:37:11

标签: sql sql-server

我有一个像这样的数据库: 第一列是城市名称。 A,B和C是具有二进制数据的列,其中1表示是,0表示否。

(数据库名称-D1)

City         A              B              C
----    ------------    -----------    --------
Boston      1               1              1
Chicago     1               0              0
Boston      1               0              0
Boston      1               1              0
Chicago     1               1              0

我想对这些城市进行分组,并在下面的A,B和C列中提供1的计数

City       Count A        Count B       Count C     
----    ------------    -----------    --------
Boston      3               2              1
Chicago     2               1              0

以下代码将给我第一栏。有没有办法我可以通过group by使用单个查询来获取所有三列?

SELECT City, COUNT(A) as Count A
FROM D1
GROUP BY City
Where City.A = 1

3 个答案:

答案 0 :(得分:7)

基本上,您可以使用sum()来代替计数。

SELECT City
    ,Sum(A) as CountA
    ,Sum(B) as CountB
    ,Sum(C) as CountC
FROM D1
GROUP BY City

如果列A, B, C的数据类型为bit,则需要将其转换为允许聚合的数据类型,即integer

SELECT City
    ,Sum(cast(A as int)) as CountA
    ,Sum(cast(B as int)) as CountB
    ,Sum(cast(C as int)) as CountC
FROM D1
GROUP BY City

答案 1 :(得分:2)

如果需要使用count(如果存在空值,则返回0),则可以在count函数中使用case语句来实现这一点。

declare @city table (
    City char(15),
    A int,
    B int,
    C int
);
insert @city (City, A, B, C)
values
('Boston', 1, 1, 1),
('Chicago', 1, 0, 0),
('Boston', 1, 0, 0),
('Boston', 1, 1, 0),
('Chicago', 1, 1, 0);

select * from @city;

select City,
       count(case when A>0 then 1 end) as CountA,
       count(case when B>0 then 1 end) as CountB,
       count(case when C>0 then 1 end) as CountC
from @city group by City;

enter image description here

答案 2 :(得分:-1)

尝试使用SUM函数,如下所示:

SELECT City
    ,Sum(A) as sum_A
    ,Sum(B) as sum_B
    ,Sum(C) as sum_C
FROM D1
GROUP BY City

请检查官方文档:SUM (Transact-SQL)