Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need to concatenate comments and group by Order in Subquery 2

Status
Not open for further replies.

dgillz

Instructor
Mar 2, 2001
10,039
US
So I have an order table and comments is a separate table. There could be several lines of comments per order, or there could be none. So my desired output should look like this:

Order_no, Order_date, Comments

So my SQL is straight forward:

Code:
select O.ord_no, O.ord_dt, C.cmt
from oeordhdr_sql O 
    left join oelincmt_sql C on O.ord_no = C.ord_no
                         and O.ord_type = C.ord_type

However If I have 3 lines of Comments I am of course getting 3 records for that Ord_no. How do I write a subquery that concatenates the comments, rendering only 1 line per order number?

Macola Software Veteran and SAP Business One Consultant on Training Wheels

Check out our Macola tools:

 
You want "a subquery that concatenates the comments, rendering only 1 line per order number"
and you are getting "just one big string" (of comments, I assume).
Isn't it just what you wanted... [ponder]

---- Andy

"Hmm...they have the internet on computers now"--Homer Simpson
 
the example you need is on to be more precise this one
Code:
SELECT Name, Pets = STUFF((SELECT N', ' + Pet 
  FROM dbo.FamilyMemberPets AS p2
   WHERE p2.name = p.name 
   ORDER BY Pet
   FOR XML PATH(N''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'')
FROM dbo.FamilyMemberPets AS p
GROUP BY Name
ORDER BY Name;
and this was on the links Andy supplied

Regards

Frederico Fonseca
SysSoft Integrated Ltd

FAQ219-2884
FAQ181-2886
 
If you have SQL Server 2017 or newer, you may use STRING_AGG

---- Andy

"Hmm...they have the internet on computers now"--Homer Simpson
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top