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
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,799 questions
SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
97 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,637 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 65,211 Reputation points
    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 7,856 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.