我有以下查询:
SELECT qn.ID,
qn.Title,
qt.Description,
l.DisplayName AS Language,
COUNT(q.ID) AS QuestionCount
FROM dbo.Questionnaires AS qn
JOIN dbo.QuestionnaireText AS qt ON qn.ID = qt.QuestionnaireID
JOIN dbo.Questions AS q ON q.QuestionnaireID = qn.ID
JOIN dbo.Languages AS l ON l.ID = qt.LanguageID
WHERE (qn.QuestionnaireTypeID = (SELECT ID
FROM QuestionnaireTypes
WHERE Value = 'Quiz'))
GROUP BY qn.ID, qn.Title, l.DisplayName, qt.Description
输出下表:
36132A45-F09C-4EB5-9BD2-34A227EC03B9 Test NULL English 1
36132A45-F09C-4EB5-9BD2-34A227EC03B9 Test NULL Spanish 1
24395BC7-A890-4514-AB35-7614E226B2A5 Quiz NULL English 1
24395BC7-A890-4514-AB35-7614E226B2A5 Quiz NULL Spanish 1
03B13E61-6D7F-4597-8BB6-83889C7BFE29 G Quiz NULL English 6
03B13E61-6D7F-4597-8BB6-83889C7BFE29 G Quiz NULL Spanish 6
我需要的是查询输出以下内容:
36132A45-F09C-4EB5-9BD2-34A227EC03B9 Test NULL English, Spanish 1
24395BC7-A890-4514-AB35-7614E226B2A5 Quiz NULL English, Spanish 1
03B13E61-6D7F-4597-8BB6-83889C7BFE29 G Quiz NULL English, Spanish 6
我现在处于亏损状态。有什么建议?
答案 0 :(得分:1)
这是您使用For Xml
:
SELECT qn.ID,
qn.Title,
qt.Description,
STUFF(
ISNULL((SELECT ', ' + l.DisplayName
FROM dbo.Languages AS l
WHERE l.ID = qt.LanguageID
GROUP BY l.DisplayName
FOR XML PATH (''), TYPE).value('.','VARCHAR(max)'), ''), 1, 2, '')
as Languages,
COUNT(q.ID) AS QuestionCount
FROM dbo.Questionnaires AS qn
JOIN dbo.QuestionnaireText AS qt ON qn.ID = qt.QuestionnaireID
JOIN dbo.Questions AS q ON q.QuestionnaireID = qn.ID
JOIN dbo.QuestionnaireTypes AS qtypes ON qtypes.Id = qn.QuestionnaireTypeID
WHERE qtypes.Value = 'Quiz'
GROUP BY qn.ID, qn.Title, l.DisplayName, qt.Description
请注意,我还将WHERE
条件移至另一个JOIN
。