簡體   English   中英

排除總和大於1的記錄

[英]Exclude records that have sum greater than 1

我有查詢返回的已訂閱頻道xyz或所有其他頻道的客戶的詳細信息。 為了生成此結果,我使用以下查詢:

select customerID
,sum(case when channel='xyz' then 1 else 0 end) as 'xyz Count'
,sum(case when channel<>'xyz' then bundle_qty else 0 end) as 'Other'
From temptable

所以我的問題是,我如何排除已訂閱2個頻道的客戶,其中一個是xyz,另一個是另一個頻道。

select customerID
      ,sum(case when channel='xyz' then 1 else 0 end) as 'xyz Count'
      ,sum(case when channel<>'xyz' then bundle_qty else 0 end) as 'Other'
From temptable
group by customerID
having sum(case when channel= 'xyz' then 1 else 0 end) > 0
   and sum(case when channel<>'xyz' then 1 else 0 end) > 0

首先,您的查詢不正確。 它需要一個group by 其次,您可以使用having

select customerID,
       sum(case when channel = 'xyz' then 1 else 0 end) as xyz_Count,
       sum(case when channel<>'xyz' then bundle_qty else 0 end) as Other
From temptable
group by customerID
having count(*) = 2 and
       sum(case when channel = 'xyz' then 1 else 0 end) = 1;

如果客戶可以多次訂閱同一頻道,而您仍然只希望“ xyz”和另一個頻道,則:

having count(distinct channel) = 2 and
       (min(channel) = 'xyz' or max(channel) = 'xyz')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM