2

我正在处理一个查询,我必须在具有多个日期范围的零件上找到 3 个或更多订单。我遇到的问题是,查询似乎没有专门查看日期范围......它正在查看完整的日期范围。

 SELECT partnumber, count(orders.partorderid) as numberoforders 
 FROM orders
 WHERE(orderdate between '2013-10-07' and '2013-10-13') or (orderdate between '2013-10-14' and '2013-10-20')
 GROUP BY partnumber
 HAVING COUNT(partorderid) > 2  

查询返回 10/07-10/20 之间的订单数,而不是 10/07-10/13 和 10/14-10/20?

4

1 回答 1

2

尝试这个:

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 之前的订单。

于 2013-10-29T20:34:32.793 回答