Answer the question
In order to leave comments, you need to log in
How to perform aggregation in T-sql like group_concat in MySQL?
The ItemCodes table has fields:
ItemCode ProjectId
A P1
A P2
A P3
B P2
C P1
C P3
ItemCode '# of Projects' ProjectIdList
A 3 P1,P2,P3
B 1 P2
C 2 P1, P3
SELECT
[ItemCode],
COUNT([ProjectId]) as ProjectsCnt,
STUFF((
SELECT ','+[ProjectId] FROM [ItemCodes]
WHERE [ProjectId]=C.[ProjectId]
GROUP BY [ItemCode]
FOR XML PATH('')
) , 1 , 1 , '' ) AS ProjectIds
FROM [ItemCodes] C
GROUP BY [ItemCode]
Column '..ProjectId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Answer the question
In order to leave comments, you need to log in
It turned out something like this query:
SELECT
[ItemCode],
COUNT([ProjectId]) as ProjectsCnt,
ProjectIds AS ProjectId
FROM [ItemCodes] C
CROSS APPLY (
SELECT ','+[ProjectId] FROM [ItemCodes]
WHERE [ProjectId]=C.[ProjectId]
GROUP BY [ItemCode],[ProjectId]
FOR XML PATH('')
) D (ProjectIds)
GROUP BY [ItemCode]
We'll have to sql xenm-a little "cheat"
SELECT
[ItemCode],
COUNT([ProjectId]) as ProjectsCnt,
min(
STUFF((
SELECT ','+[ProjectId] FROM [ItemCodes]
WHERE [ProjectId]=C.[ProjectId]
GROUP BY [ItemCode]
FOR XML PATH('')
) , 1 , 1 , '' )
) AS ProjectIds
FROM [ItemCodes] C
GROUP BY [ItemCode]
SELECT ItemCode,
COUNT(ProjectId) AS [ProjectsCnt],
(SELECT STRING_AGG(IC.ProjectId, ', ')
FROM ItemCodes AS IC WHERE (IC.ItemCode = ItemCodes.ItemCode)) AS [ProjectIds]
FROM ItemCodes
GROUP BY ItemCode
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question