我有一个很好的查询,效果很好:
select distinct f.client_id
from f_accession_daily f
left join SalesDWH..TestPractices tests
on tests.ClientID=f.CLIENT_ID
where tests.ClientID is null
group by f.client_id
having max(f.received_date) between '20120601' and '20120630'
我需要将结果集限制为仅f.client_id
,其中特定f.client_id
的计数(*)在过去一个月(即'20120501'和'之间)为40或更高20120530' )
这是我试过的:
select distinct f.client_id
from f_accession_daily f
left join SalesDWH..TestPractices tests
on tests.ClientID=f.CLIENT_ID
where tests.ClientID is null
group by f.client_id
having max(f.received_date) between '20120601' and '20120630'
) NotOrderedIn6Months
on f.CLIENT_ID=NotOrderedIn6Months.CLIENT_ID
right join
(select client_id,COUNT(*) count from F_ACCESSION_DAILY
where RECEIVED_DATE between '20120501' and '20120530'
group by CLIENT_ID
having COUNT(*)>=40
) Having40
on Having40.CLIENT_ID=f.CLIENT_ID
答案 0 :(得分:1)
预先汇总上个月的数据(5月份有31天,而不是30天),然后加入。
select f.client_id
from f_accession_daily f
join (
select client_id
from f_accession_daily
where received_date between '20120501' and '20120531'
group by client_id
having count(*) >= 40
) A on A.client_id = f.client_id
left join SalesDWH..TestPractices tests
on tests.ClientID=f.CLIENT_ID
where tests.ClientID is null
group by f.client_id
having max(f.received_date) between '20120601' and '20120630';
另请注意,当您已经拥有GROUP BY时,您将不需要DISTINCT。
答案 1 :(得分:1)
添加
AND f.client_id IN
(SELECT client_id FROM F_ACCESSION_DAILY
WHERE RECEIVED_DATE BETWEEN '20120501' AND '20120530'
GROUP BY client_id
HAVING COUNT(*) >= 40)
到原始查询的where子句。