在这种情况下,如何将行连接到动态列?

时间:2014-01-11 11:48:06

标签: sql sql-server-2008 stored-procedures

我很抱歉发布这个,我觉得,几乎重复。但是我已经尝试了我找到的解决方案,但还没有让它在我的解决方案中起作用:(

这是我在FUBAR之前看到的SQL。这将以非常好的格式返回数据。但是我得到了具有相同数据的重复行,除了问题和答案都已更改。我希望问题是列名和答案值。

SELECT c.*, sa.Question, sa.Answer
    FROM Customers as c, Surveys s, SurveyAnswers sa 
    WHERE c.OrderID IN(SELECT id FROM @orders)
        AND s.CustomerID = c.id
        AND sa.SurveyID = s.ID

我的SQL很弱,我必须尽快完成这项工作:(另一种方法是在.net应用程序中执行更繁重的工作,但我很乐意直接获取数据 最好的祝福, 的Mikael

1 个答案:

答案 0 :(得分:0)

您希望使用Bluefeet's answer here来完成动态列枢轴。 (为简洁起见,我省略了你的@orders过滤器):

DECLARE 
  @cols AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(sa.Question) 
            FROM SurveyAnswers sa
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT CustomerID, Name, ' + @cols + ' from 
            (
                select 
                    c.ID as CustomerId, 
                    c.Name,
                    sa.Question, 
                    sa.Answer
                FROM Customers as c
                     INNER JOIN Surveys s ON s.CustomerID = c.id
                     INNER JOIN SurveyAnswers sa ON sa.SurveyID = s.ID
           ) x
            pivot 
            (
                min(Answer)
                for Question in (' + @cols + ')
            ) p '
 execute(@query);

SqlFiddle here