2017-09-26 218 views
0

在事务表中,有order_ID(PK),transaction_date,cus_ID,store_ID。 现在我需要通过cus_ID,count(store_ID)= 1来获取所有cus_ID。但有一个例外 - 当cus_ID只有store_ID ='999'的订单时。 交易日期应为过去365天。 我有如下代码:如何排除使用group by和count时的特殊条件()

Select cus_ID, count(store_ID) as store_count 
From trn_header 
where transanction_date From '7/30/2017' - 365 To '7/30/2017' 
group by cus_ID having store_count = 1 

我只是不知道如何排除在 '999' 条件... 感谢

+0

当'store_ID ='999''那么什么?它听起来像你需要一个CASE的陈述,但我并不理解你的逻辑。 – Simon

+0

如果一个cust_id的所有订单都是store_ID ='999',它应该被我的查询排除。 –

回答

0

的正确的答案应该是这样的:

select distinct cus_id, store_id from 
(select cus_id,count(distinct store_id) as freq 
from a 
where transaction_date between @begin_date and @end_date 
group by cus_id 
having count(distinct store_id) = 1 
) b, a where a.cus_id = b.cus_id and store_id <> '999' 
0
Select cus_ID, count(store_ID) as store_count 
From trn_header 
where transanction_date From '7/30/2017' - 365 To '7/30/2017' And store_ID<>'999' 
group by cus_ID having store_count = 1 

希望它可以帮助

+0

找出来,因为我应该使用子查询来排除store_id ='999'的情况;我的问题存在误解。对于那个很抱歉。 –