Skip to content
Advertisement

How to select rows in parent table based on a value in child table

Consider the following tables, what would be an efficient query to return 1 row for each order that has at least 1 child row with a specific warehouse code? I am using SQL Server 2016.

Table: Orders
OrderNo OrderDt    Status Type
------- ---------- ------ --------
200123  11/20/2020 NEW    SHIPPING
200124  11/21/2020 NEW    IN-STORE
200125  11/21/2020 NEW    SHIPPING
Table: OrderItems
OrderNo ItemCode Warehouse
------- -------- ---------
200123  Item1    10
200124  Item1    10
200124  Item2    20
200125  Item2    20

If I query for Warehouse 10:

OrderNo OrderDt    Status Type
------- ---------- ------ --------
200123 11/20/2020  NEW    SHIPPING
200124 11/21/2020  NEW    IN-STORE

If I query for Warehouse 20:

OrderNo OrderDt    Status Type
------- ---------- ------ --------
200124  11/21/2020 NEW    IN-STORE
200125  11/21/2020 NEW    SHIPPING

Advertisement

Answer

Assuming that when you say “When I query for Warehouse X” you are running individual queries for a single warehouse, just a simple INNER JOIN and a WHERE clause should do it:

SELECT DISTINCT o.OrderNo, o.OrderDt, o.Status, o.Type
FROM Orders o
INNER JOIN OrderItems oi ON o.OrderNo = oi.OrderNo
WHERE Warehouse = 10;

SELECT DISTINCT o.OrderNo, o.OrderDt, o.Status, o.Type
FROM Orders o
INNER JOIN OrderItems oi ON o.OrderNo = oi.OrderNo
WHERE Warehouse = 20;

If you want to have everything in one result set add ItemCode and Warehouse to the query and leave out the WHERE clause.

SELECT
    o.OrderNo,
    o.OrderDt,
    o.Status,
    o.Type,
    oi.ItemCode,
    oi.Warehouse
FROM Orders o
INNER JOIN OrderItems oi ON o.OrderNo = oi.OrderNo;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement