如何在使用group by和count()

时间:2017-09-26 03:18:11

标签: sql-server group-by count

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

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

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

2 个答案:

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

希望它有所帮助

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