SQL多日期查询

时间:2013-10-29 20:28:19

标签: sql

我正在进行查询,我必须在具有多个日期范围的零件上找到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 ???

1 个答案:

答案 0 :(得分: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之前的订单。