SQL 使用多列进行不同计数的查询

SQL query with count distinct using multiple columns

SQL 服务器中有以下 table:

create table [dbo].[stats](
    [customerid] [int] NOT NULL,
    [username] [nvarchar](256) NOT NULL,
    [source] [int] NOT NULL,
    [destination] [int] NOT NULL,
    [date] [smalldatetime] NOT NULL
) 

填充了数据:

customerid  username    source  destination date
1           user1         1        1        2022-05-06 00:00:00
1           user2         2        1        2022-05-06 00:00:00
1           user21        1        2        2022-05-06 00:00:00

有没有一种方法可以创建一个查询来显示有多少 unique 用户使用了每个 customerid 的每种类型的源和目标?

使用上面的示例,我希望得到以下输出:

customerid source1 source2 destination1 destination2
1            2        1         2           1 

伪查询:

select customerid,
    count(distinct(username + source)) where source = 1) as source1,
    count(distinct(username + source)) where source = 2) as source2,
    count(distinct(username + destination)) where destination = 1) as destination1,
    count(distinct(username + destination)) where destination = 2) as destination2,
from stats
group by customerid
select userID, source, destination, count(*)
from stats
group by userID, source, destination

看来你只需要一个条件计数

select customerid, 
    Count(case when source=1 then 1 end) Source1,
    Count(case when source=2 then 1 end) Source2,
    Count(case when destination=1 then 1 end) destination1,
    Count(case when destination=2 then 1 end) destination2
from stats
group by customerid;

你可以用案例

select 
  customerid,
  count(distinct(case 
                 when source = 1
                 then username
                 End)) as source1,
    count(distinct(case
                 when source = 2
                 Then username
                 End )) as source2,
    count(distinct(case 
                 when destination = 1
                 Then username
                 End)) as destination1,
    count(distinct(case
                 when destination = 2
                 Then username
                 End)) as destination2,
from stats
group by customerid;