how to return with a nested query two columns from the same table but different results

Jonathan Brotto 420 Reputation points
2024-08-22T16:12:30.3366667+00:00

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.

SQL Server SQL Server Transact-SQL
Developer technologies Transact-SQL
SQL Server Other
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-08-22T16:17:07.2366667+00:00

    without a schema and sample data all we can say is use a join (left if optional) or sub query.


  2. Naomi Nosonovsky 8,431 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' ;
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.