(SQL)一行查询结果

时间:2016-04-08 08:25:16

标签: sql-server database sql-server-2014-express

所以我有两张桌子,名为"问题"和答案 Diagramm

我为这两个表做了一个INNER JOIN

SELECT Questions.ID, Questions.QText, Answers.AText
FROM Questions INNER JOIN Answers
ON Questions.ID=Answers.QuestionID;

结果如下: Result 但是,您可以清楚地看到,每次使用答案时,问题会显示4次。

现在我的问题是:是否可以将结果放在一行中,由

组成

[ID] - [问题] - [答案1] - [答题2] - [答案3] - [答案4]

3 个答案:

答案 0 :(得分:2)

对CSV使用CROSS APPLY。不要内联,然后你需要分组...

SELECT q.ID, q.QText, Answers = STUFF(x.csv, 1, 1, '')
FROM Questions q
CROSS APPLY
    (
    SELECT
        '-' + a.Atext
    FROM
        Answers a
    WHERE
        a.QuestionID = q.ID
    FOR XML PATH ('')
    ) x (csv)

答案 1 :(得分:1)

使用COALESCE

获取问题及其所有答案
DECLARE @Answer VARCHAR(8000) 
SELECT Questions.ID, Questions.QText, @Answer = COALESCE(@Answer + ', ', '') + AText
FROM Questions INNER JOIN Answers ON Questions.ID=Answers.QuestionID
WHERE AText IS NOT NULL

如果您使用的是SQL Server 2005,则可以使用FOR XML PATH命令。<​​/ p>

SELECT Questions.ID, Questions.QText,
       (STUFF((SELECT CAST(', ' + [AText] AS VARCHAR(MAX)) 
               FROM Answers 
               WHERE Questions.ID = Answers.QuestionID
         FOR XML PATH ('')), 1, 2, '')) AS Answers
 FROM Questions

答案 2 :(得分:1)

您可以将此查询用于数据透视表:

SELECT QID, QText, [1], [2], [3], [4]
FROM (SELECT Q.ID AS QID, A.ID AS AID, Q.QText, A.AText FROM Questions AS Q 
INNER JOIN Answers AS A ON Q.ID = A.QuestionID) QA
PIVOT
(
    MAX(AText)
    FOR AID
    IN ([1], [2], [3], [4])
) AS PV

但是:您必须为答案表使用组合主键。 使用此数据透视表,答案ID每次必须为1,2,3,4。否则你不会得到你的答案。 FOR AID声明,哪一列用于此目的。 否则你可以在答案中添加一个列,这些答案叫做&#34; AnswerNr&#34;或类似的东西。在此列中,您将1到4作为答案,并将查询更改为:

SELECT QID, QText, [1], [2], [3], [4]
FROM (SELECT Q.ID AS QID, ->A.AnswerNr<-, Q.QText, A.AText FROM Questions AS Q 
INNER JOIN Answers AS A ON Q.ID = A.QuestionID) QA
PIVOT
(
    MAX(AText)
    FOR ->AnswerNr<-
    IN ([1], [2], [3], [4])
) AS PV