排除总和大于1的记录

时间:2018-01-24 00:12:01

标签: sql sql-server sum case

我查询了订阅频道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,另一个是另一个频道。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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;

如果客户可以多次订阅同一频道,您仍然只需要&#34; xyz&#34;然后是另一个渠道:

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