Sql 向查询添加筛选器

Sql 向查询添加筛选器,sql,sql-server,sql-server-2008,tsql,Sql,Sql Server,Sql Server 2008,Tsql,我有一个很好的查询: 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' 我需要

我有一个很好的查询:

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
的计数(*)在上个月为40或更大(即在“20120501”和“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

预先汇总上个月的数据(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';
另外请注意,当您已经有分组依据时,您不需要使用DISTINCT。

只需添加

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子句