SQL Server:如何获取每个组的DISTINCT计数

问题描述 投票:0回答:1

我有一张这样的桌子:

enter image description here

我想获得每个组的不同计数:

enter image description here

如何获得结果?谢谢。

sql-server count distinct
1个回答
1
投票

您可以使用条件聚合:

select group,
       sum(case when location = 'A' then 1 else 0 end) as a,
       sum(case when location = 'B' then 1 else 0 end) as b,
       sum(case when location = 'C' then 1 else 0 end) as c
from t
group by group;

请注意,group对于列而言是非常差的名称,因为它是SQL保留字。

© www.soinside.com 2019 - 2024. All rights reserved.