Wednesday, September 14, 2016

Concatenating the same column from different rows in a sql query

SELECT DISTINCT a.Author,
 Books = STUFF(( SELECT ', ' + BookTitle
   FROM Books as b
   WHERE b.Author=a.Author 
   ORDER BY BookTitle
   FOR XML PATH('')
   ), 1, 1, '')
FROM Books as a
INNER JOIN (
 SELECT Author, COUNT(BookTitle) as BookCount
 FROM Books
 WHERE NOT Author IS NULL
 GROUP BY Author
 HAVING COUNT(BookTitle) > 5) as c ON a.Author=c.Author

No comments:

Post a Comment