troubleshooting Question

MySQL query, not able to get correct result with Where, Group by and having

Avatar of practitioner
practitionerFlag for Singapore asked on
27 Comments2 Solutions183 ViewsLast Modified:
A table stores order status at various stages,
Pending (1), when the order is placed,
Processing (2), when the packaging and shipping starts,
Delivered (3), when it reaches the customer.

Following shows with sample data how it is stored, first 3 records say that order #200 is Delivered on 17th March, Processing on 16th March, Pending on 15th March:
orders_status_history_id, orders_id, orders_status_id, date_added
409,                      200,       3,                2010-03-17
408,                      200,       2,                2010-03-16
407,                      200,       1,                2010-03-15
405,                      196,       2,                2010-03-15
404,                      196,       1,                2010-03-14
7,                        2,         3,                2009-08-04

Open in new window

I want to list all the orders where there is only one status which is Pending (1), this order should not have other status e.g. Processing (2) or Delivered (3)

So I wrote this query but I'm not sure how correct it is:

SELECT  `orders_id`
FROM  `orders_status_history`
GROUP BY  `orders_id`
HAVING COUNT(`orders_status_id`) = 1
ORDER BY `orders_id`


Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 2 Answers and 27 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 27 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros