1

我正在运行以下 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 声明吗?

4

2 回答 2

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)
于 2013-01-10T15:35:29.277 回答
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
于 2013-01-10T15:32:27.723 回答