Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")

>Solution :

SELECT 
    Ord_Partno, Ord_UnitPrice, Ord_Qty, 
    AtlantaInv.Stock AS Atlanta,
    ChicagoInv.Stock AS Chicago,
    case when (AtlantaInv.Stock >= Ord_Qty OR ChicagoInv.Stock >= Ord_Qty) then 'Yes' else 'No' end as InStock
FROM 
    Orders 
INNER JOIN 
    Inventory AS AtlantaInv ON Ord_Partno = AtlantaInv.Inv_Partno and AtlantaInv.Inv_Warehouse = "Atlanta"
INNER JOIN 
    Inventory AS ChicagoInv ON Ord_Partno = ChicagoInv.Inv_Partno and ChicagoInv.Inv_Warehouse = "Chicago"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading