2

I'm working on a query where I have to find 3 or more orders on a part that will have multiple date ranges. The problem I'm having is that it looks like the query isn't looking at the date ranges specifically...it's looking at a complete range of dates.

 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  

The query returns the numberoforders between 10/07-10/20, not 10/07-10/13 and 10/14-10/20???

0

1 Answer 1

2

Try this:

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

Or you might prefer:

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

which has a less repetition.

FYI, if orderdate is a date, you are fine. But if it has and date a and a non-zero time, you will be missing orders that are after 2013-10-13 00:00:00 and before 2013-10-14 00:00:00.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the quick reply! The only problem I'm having with this is that it shows blanks or < 3 in week1 or week2 if one of the conditions are met. Can these values be eliminated from the results?
It depends what you mean by eliminated. Do you want to have the value in the offending column as NULL, or remove the whole record for the part number?
Remove the record for the part number from the query results.
Easy...simply change WHERE week1 > 2 OR week2 > 2 TO WHERE week1 > 2 AND week2 > 2
I was never able to get the second example to run due to an incorrect syntax error near WHERE. I changed the OR to AND in the HAVING clause from the first example and the output is great, but now it's missing values. Some of the orders that were > 3 aren't pulling.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.