Попробуйте изменить запрос следующим образом:
SELECT
ContactId,
Intent + ' (' + CONVERT(VARCHAR,COUNT(Intent)) + ')' as Intents,
[Transcript] = STUFF((SELECT ' ,' + LTRIM(RTRIM(b.Transcript))
FROM ACCOUNT_DATA b
WHERE b.ContactId = a.ContactId
AND b.Intent = a.Intent
FOR XML PATH('')), 1, 2, '')
FROM
ACCOUNT_DATA a
GROUP BY
ContactId, Intent
ORDER BY
ContactId
Вот демоверсия
или если вы хотите объединить Intent
и Transcript
SELECT
ContactId,
Intent + ' (' + CONVERT(VARCHAR,COUNT(Intent)) + ') : ' +
STUFF((SELECT ' ,' + LTRIM(RTRIM(b.Transcript))
FROM ACCOUNT_DATA b
WHERE b.ContactId = a.ContactId
AND b.Intent = a.Intent
FOR XML PATH('')), 1, 2, '') AS "Intent + Transcript"
FROM
ACCOUNT_DATA a
GROUP BY
ContactId, Intent
ORDER BY
ContactId
Редактировать: последний запрос
SELECT DISTINCT ContactId, [Transcript]=STUFF((SELECT '; ' + IntentTranscript
FROM (
SELECT a.ContactId,
a.Intent + ' (' + CONVERT(VARCHAR,COUNT(a.Intent)) + ') : ' +
STUFF((SELECT ' ,' + LTRIM(RTRIM(b.Transcript))
FROM ACCOUNT_DATA b
WHERE b.ContactId = a.ContactId
AND b.Intent = a.Intent
FOR XML PATH('')), 1, 2, '') AS "IntentTranscript"
FROM ACCOUNT_DATA a
GROUP BY a.ContactId, a.Intent
) c
WHERE c.ContactId = INNER_ACCOUNT_DATA.ContactId
FOR XML PATH('')), 1, 2, '')
FROM
(
SELECT a.ContactId,
a.Intent + ' (' + CONVERT(VARCHAR,COUNT(a.Intent)) + ') : ' +
STUFF((SELECT ' ,' + LTRIM(RTRIM(b.Transcript))
FROM ACCOUNT_DATA b
WHERE b.ContactId = a.ContactId
AND b.Intent = a.Intent
FOR XML PATH('')), 1, 2, '') AS "IntentTranscript"
FROM ACCOUNT_DATA a
GROUP BY a.ContactId, a.Intent
) AS INNER_ACCOUNT_DATA
ORDER BY ContactId
Вот демоверсия