Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

sql server - Using T-SQL for Grouping, concatenating and counting


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use aggregation in the subquery:

SELECT p.ProductID,
       ISNULL(STUFF( (SELECT CONCAT('-', p2.DefectCode, '(', COUNT(*), ')')
                      FROM Product p2
                      WHERE p2.ProductID = p.ProductID
                      GROUP BY p2.DefectCode
                      FOR XML PATH ('')
                     ), 1, 1, ''
                   ), '') AS Defects    
FROM Product p
GROUP BY p.ProductID;

I assume you are using an older version of SQL Server that doesn't support STRING_AGG().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...