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()
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…