SQL Pivot显示用户问卷回复?

时间:2013-01-10 15:31:05

标签: sql sql-server sql-server-2008-r2 pivot

我正在运行以下SQL语句

SELECT
 su.Id
  ,rp.QuestionId
  ,rp.AnswerId
FROM SiteUser su
  JOIN Response rp ON su.Id = rp.SiteUserId
  JOIN Answer an ON rp.AnswerId = an.Id

这导致以下输出

UserId    QuestionId    AnswerId
--------------------------------
1         1             1
1         2             6
2         1             2
2         2             3
3         1             2
3         2             2

我想实现以下输出

UserId    Question1   Question2
-------------------------------
1         1           6
2         2           3
3         2           2

任何人都可以帮助编写Pivot声明吗?

2 个答案:

答案 0 :(得分:2)

如果您使用的是带有PIVOT函数的RDBMS(SQL Server 2005 + / Oracle),那么您可以使用:

select Id, [1] As Question1, [2] as Question2
from
(
  SELECT su.Id
    ,rp.QuestionId
    ,rp.AnswerId
  FROM SiteUser su
  INNER JOIN Response rp 
    ON su.Id = rp.SiteUserId
  INNER JOIN Answer an 
    ON rp.AnswerId = an.Id
) src
pivot
(
  max(AnswerId)
  for QuestionId in ([1], [2])
) piv

如果您使用的是SQL Server,那么您对问题ID的值有未知数量,那么您可以使用动态SQL来获得相同的结果:

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

select @colsPivot = STUFF((SELECT distinct ', ' + QUOTENAME(QuestionId) 
                    from Response 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsFinal = STUFF((SELECT distinct ', ' + QUOTENAME(QuestionId) + ' as Question'+QuestionId 
                    from Response 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT id, ' + @colsFinal + ' from 
             (
                SELECT su.Id
                  ,rp.QuestionId
                  ,rp.AnswerId
                FROM SiteUser su
                INNER JOIN Response rp 
                  ON su.Id = rp.SiteUserId
                INNER JOIN Answer an 
                  ON rp.AnswerId = an.Id
            ) src
            pivot 
            (
                max(AnswerId)
                for QuestionId  in (' + @colsPivot + ')
            ) p '

execute(@query)

答案 1 :(得分:1)

因为您没有提到任何RDBMS,所以下面的查询几乎适用于所有RDBMS。

SELECT  su.Id,
        MAX(CASE WHEN rp.QuestionId = 1 THEN rp.AnswerId ELSE NULL END) Question1,
        MAX(CASE WHEN rp.QuestionId = 2 THEN rp.AnswerId ELSE NULL END) Question2
FROM    SiteUser su
        INNER JOIN Response rp 
            ON su.Id = rp.SiteUserId
        INNER JOIN Answer an 
            ON rp.AnswerId = an.Id
GROUP BY su.Id