0

我有以下查询:

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

在这一点上,我不知所措。有什么建议么?

4

1 回答 1

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.

于 2013-07-11T01:12:06.873 回答