Having trouble with simple select query where all ordere item statuses = shipped

  • I'm trying to write a simple query but having trouble returning the correct results.  I have a table of items that have been ordered.  Within this table, there are several different statuses an order can be in (i.e. open, pending, shipped, cancelled, etc) I want to write a query to return the order id of any orders where ALL items have a status of 'shipped'.

    Here's a sample:

    Order Items Table:

    OrderItemId   |   OrderId     |      ItemId    |     Status


    111                   |      123           |        999        |     Shipped

    112                  |     123            |         888       |     Shipped

    113                  |   456             |         777        |     Shipped

    114                 |  456              |          666       |    Open

    In the above query, I want to return OrderId  123 because all items within the order have shipped.  OrderId 456 still has an open item, so I don't want to include that one.

    Thanks

     

  • Group by OrderID and put in a HAVING clause where you check that the MAX value of Status is Shipped, and the MIN value of Status is Shipped.

    John

  • So you want to show only orders where all items of the order have the status of shipped?

    This might not be the "correct" way which may have been mentioned above but this is probably how I'd do it because I'm a noob at sql

    SELECT  ORDERid
    FROM OrderTable
    WHERE Orderid NOT IN (SELECT orderid FROM OrderTable WHERE status <> 'Shipped')
  • Is there an Order table? Typically, there is an Order and OrderDetail (or in your case OrderItems) to relate the order to the order items. If not, where does the OrderId come from?

    Alan H
    MCSE - Data Management and Analytics
    Senior SQL Server DBA

    Best way to ask a question: http://www.sqlservercentral.com/articles/Best+Practices/61537/

  • SELECT o1.*
    FROM OrderItem o1
    WHERE NOT EXISTS (SELECT 1 FROM OrderItem o2 where o1.OrderId = o2.OrderId and o2.Status <> 'Shipped')

    If you haven't even tried to resolve your issue, please don't expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.

  •  

    SELECT OrderId
    FROM OrderItems
    GROUP BY OrderId
    HAVING SUM(CASE WHEN Status = 'Shipped' THEN 1 ELSE 0 END) < COUNT(*)

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply