Skip to content
Advertisement

SQL multirow data on one row

I almost never ask a question, so please be patient with me.

Example Orders table:

Order_ID Ord_Partno Ord_UnitPrice Ord_Qty
1658712 PN001 $1.20 9
1658712 PN002 $2.40 4
1658712 PN003 $1.40 21
1658712 PN004 $1.10 16

Example Inventory table:

Inv_Partno Inv_Warehouse Stock
PN001 Atlanta 14
PN001 AtlantaHold 0
PN001 Chicago 7
PN001 ChicagoHold 0
PN002 Atlanta 5
PN002 AtlantaHold 18
PN002 Chicago 0
PN002 ChicagoHold 0
PN003 Atlanta 2
PN003 AtlantaHold 43
PN003 Chicago 19
PN003 ChicagoHold 0

In this example, each part in Inventory has 4 warehouse entries. The actual stock available, and the amount in Holding for other orders. If either warehouse (Atlanta or Chicago, NOT Hold) has more stock than Ord_Qty (but not combined), I would like to get following result given an Order_ID:

Ord_Partno Ord_UnitPrice Ord_Qty Atlanta Chicago InStock
PN001 $1.20 9 14 7 Yes
PN002 $2.40 4 5 0 Yes
PN003 $1.40 21 2 19 No
PN004 $1.10 16 8 9 No

As a beginner I have not been able to replicate this result. I have tried using DISTINCT, LEFT/INNER JOIN, CASE + EXISTS ect. Could anyone help me out with this?

Example query:

SELECT DISTINCT
    Ord_Partno, Ord_UnitPrice, Ord_Qty, 
    () AS Atlanta, () AS Chicago, () AS InStock 
FROM 
    Orders 
INNER JOIN 
    Inventory ON Ord_Partno = Inv_Partno
WHERE
    Order_ID = 1658712 
    AND (Inv_Warehouse = "Atlanta" OR Inv_Warehouse = "Chicago")

Advertisement

Answer

SELECT 
    Ord_Partno, Ord_UnitPrice, Ord_Qty, 
    COALESCE(AtlantaInv.Stock, 0) AS Atlanta,
    COALESCE(ChicagoInv.Stock, 0) AS Chicago,
    case when (AtlantaInv.Stock >= Ord_Qty OR ChicagoInv.Stock >= Ord_Qty) then 'Yes' else 'No' end as InStock
FROM 
    Orders 
LEFT JOIN 
    Inventory AS AtlantaInv ON Ord_Partno = AtlantaInv.Inv_Partno and AtlantaInv.Inv_Warehouse = 'Atlanta'
LEFT JOIN 
    Inventory AS ChicagoInv ON Ord_Partno = ChicagoInv.Inv_Partno and ChicagoInv.Inv_Warehouse = 'Chicago'
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement