0

我有一个很好的查询:

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
4

2 回答 2

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

于 2012-11-28T22:58:20.380 回答
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。

于 2012-11-28T22:47:44.367 回答