1

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

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

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

我不知道该怎么做,因为在我的表中我有垂直排列的数据,但是输出希望数据是水平的。

请帮助我。

4

1 回答 1

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)

输出(类似这样的东西

╔════╦═══════╦═════════════════════════╦══════════════════════╗
║ ID ║ NAME  ║ DID YOU LIKE OUR EVENT? ║ WILL YOU COME AGAIN? ║
╠════╬═══════╬═════════════════════════╬══════════════════════╣
║  1 ║ AHMED ║ bla bla                 ║ Yes                  ║
╚════╩═══════╩═════════════════════════╩══════════════════════╝
于 2013-05-29T07:37:32.297 回答