尝试这个:
SELECT partnumber,
SUM(CASE WHEN orderdate BETWEEN '2013-10-07' and '2013-10-13' THEN 1 END) week1,
SUM(CASE WHEN orderdate BETWEEN '2013-10-14' and '2013-10-20' THEN 1 END) week2
FROM orders
GROUP BY partnumber
HAVING SUM(CASE WHEN orderdate BETWEEN '2013-10-07' and '2013-10-13' THEN 1 END) > 2
AND SUM(CASE WHEN orderdate BETWEEN '2013-10-14' and '2013-10-20' THEN 1 END) > 2
或者您可能更喜欢:
SELECT *
FROM (
SELECT partnumber,
SUM(CASE WHEN orderdate BETWEEN '2013-10-07' and '2013-10-13' THEN 1 END) week1,
SUM(CASE WHEN orderdate BETWEEN '2013-10-14' and '2013-10-20' THEN 1 END) week2
FROM orders
GROUP BY partnumber
) t WHERE week1 > 2 AND week2 > 2
重复次数较少。
仅供参考,如果orderdate
是约会,你很好。但如果它的日期为 a 和非零时间,您将丢失 2013 年 10 月 13 日 00:00:00 之后和 2013 年 10 月 14 日 00:00:00 之前的订单。