without a schema and sample data all we can say is use a join (left if optional) or sub query.
how to return with a nested query two columns from the same table but different results
Jonathan Brotto
420
Reputation points
I have a query where it is a parent query returning results then other results from another table but that table would have two results I would like such as a bill to and ship to where I would like one in each column in the parent query but in the child table are two line items. how would I go about that?
I am thinking of a nested query within the select statement. it has been awhile. any approach works for me.
2 answers
Sort by: Most helpful
-
-
Naomi Nosonovsky 7,881 Reputation points
2024-08-23T13:50:29.4866667+00:00 Try using OUTER APPLY for both current left joins and include reftype condition as part of the WHERE in these OUTER APPLY statements, e.g.
SELECT h.OrderNumber, h.OrderDate, h.ProcessDate, h.ProcessDate, h.ShipTo, h.branch, h.PartnerID, b.RefType, b.RefValue as BillTo, -- guessing here s.RefType, s.RefValue as ShipTo, -- guessing here i.VeritivProductCode as 'Compass Code', i.CustomerProductCode, i.Description, i.CustDesc, i.Quantity, i.OriginalQuantity, i.UM, i.CustUM, i.PricePer, i.UnitPrice,i.LineComments AS 'Customer UM', i.CustomerLineNumber, i.UPC FROM inbound850.tb_InboundOrdersHeaders H INNER JOIN inbound850.InboundOrdersItems I ON H.ID = I.HeaderID OUTER APPLY (SELECT TOP (1) * from inbound850.tb_InboundOrdersReferences b WHERE H.ID = B.HeaderID and b.RefType = 'BT_N104') b OUTER APPLY (SELECT TOP (1) * FROM inbound850.tb_InboundOrdersReferences S WHERE H.ID = S.HeaderID AND S.RefType = 'ST_N104') S WHERE h.PartnerID LIKE '%Lob%' And h.OrderDate >= '2024-07-01' ;