简体   繁体   English

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

[英]SQL query with count distinct using multiple columns

Having the following table in SQL Server: SQL服务器中有下表:

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
) 

populated with data:填充数据:

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

Is there a way to create a query to display counts of how many unique users used each type of source and destination for each customerid?有没有一种方法可以创建一个查询来显示有多少唯一用户使用了每个 customerid 的每种类型的源和目标?

Using the above sample I'd like to have the following output:使用上面的示例,我想要以下 output:

customerid source1 source2 destination1 destination2
1            2        1         2           1 

Pseudo query:伪查询:

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

You can use case你可以用例

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;
select userID, source, destination, count(*)
from stats
group by userID, source, destination

Looks like you just need a conditional count看起来你只需要一个条件计数

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM