SQL水平排列垂直信息

时间:2013-05-29 07:21:55

标签: sql tsql sql-server-2012

伙计们。我遇到了一个非常独特的情况,但我相信你们可能会遇到同样的情况。

我有四张桌子。 (他们代表填写调查表的用户)

SurveyFiller
------------

ID NAME  ORGANIZATION
1  AHMED  IBM

Questions
--------

ID Question
1  Did you like our event?
2  Will you come again?


    Answers
    -------

    ID Answers
    1  Yes
    2  No
    3  Maybe
    4  bla bla

QuestionAnswerMatrix
---------------------

ID SurveyFillerId QuestionId AnswerId
1     1              1            4
2     1              2           1
3     1              3            2

就是这样。现在我的客户希望看到调查结果,如下所示

SurveyFIllerID  Name        Did you like our event?  Will you come again?
 1              Ahmed       yes                      No

我不知道如何解决这个问题,因为在我的表格中我有垂直排列的数据, 但是输出要求数据是水平的。

请帮助我。

1 个答案:

答案 0 :(得分:1)

这是一个动态查询,即使用户没有回答问题,它也会显示结果列表中的所有可用问题。

DECLARE @colList AS NVARCHAR(MAX), @sqlStatement AS NVARCHAR(MAX)

SELECT @colList = STUFF((SELECT DISTINCT ',' + QUOTENAME(Question) 
                    FROM Questions
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') ,1,1,'')


SET @sqlStatement = 
            'SELECT ID,Name, ' + @colList + ' 
             FROM 
             (
                SELECT  a.ID, 
                        a.Name,
                        b.Question,
                        d.Answers
                FROM    SurveyFiller a
                        CROSS JOIN Questions b
                        LEFT JOIN QuestionAnswerMatrix c
                            ON  a.ID = c.SurveyFillerId AND
                                b.ID = c.QuestionId
                        LEFT JOIN Answers d
                            ON  c.AnswerId = d.ID
                WHERE   a.ID = 1
             ) dta
             pivot 
             (
                MAX(Answers)
                FOR Question IN (' + @colList + ')
             ) pvt'

EXECUTE(@sqlStatement)

OUTPUT(类似这样的

╔════╦═══════╦═════════════════════════╦══════════════════════╗
║ ID ║ NAME  ║ DID YOU LIKE OUR EVENT? ║ WILL YOU COME AGAIN? ║
╠════╬═══════╬═════════════════════════╬══════════════════════╣
║  1 ║ AHMED ║ bla bla                 ║ Yes                  ║
╚════╩═══════╩═════════════════════════╩══════════════════════╝