簡體   English   中英

SQL 使用多列進行不同計數的查詢

[英]SQL query with count distinct using multiple columns

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
) 

填充數據:

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

有沒有一種方法可以創建一個查詢來顯示有多少唯一用戶使用了每個 customerid 的每種類型的源和目標?

使用上面的示例,我想要以下 output:

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 
  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

看起來你只需要一個條件計數

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