1

我遇到的问题是我要查找的表中有多个结果。所以如果我有这个:

SELECT DISTINCT student.ident AS [Ident],
     proghist.prgc AS [Test Code]
FROM student 
LEFT OUTER JOIN proghist

对于一些学生,我得到多个“测试代码”,所以它看起来像这样:

Ident   Test Code
123456   1
123456   4
654321   2
654321   6
122222   1

有没有办法将它们组合成一行并分开列?

编辑:我希望数据出现在最终结果中:

123456 1 4 
654321 2 6 
122222 1
4

1 回答 1

3

由于您使用的是 SQL Server,如果您使用的是 SQL Server 2005+,那么您可以使用该PIVOT功能。如果您知道TestCodes每个最多只能有两个,ident那么您可以对这些值进行硬编码:

select ident,
  [1] TestCode1,
  [2] TestCode2
from
(
  SELECT  s.ident AS Ident,
    p.prgc AS TestCode,
    row_number() over(partition by s.ident order by p.prgc) rn
  FROM student s
  LEFT OUTER JOIN proghist p
    on s.ident = p.ident
) src
pivot
(
  max(TestCode)
  for rn in ([1], [2])
) piv

请参阅带有演示的 SQL Fiddle

如果您有未知数量的 值TestCodes,则可以PIVOT对数据使用动态 SQL:

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(rn)
                    FROM
                    (
                      select cast(row_number() over(partition by s.ident order by p.prgc) as varchar(50)) rn
                      FROM student s
                      LEFT OUTER JOIN proghist p
                        on s.ident = p.ident
                    ) src
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsPivot = STUFF((SELECT distinct ',' + QUOTENAME(rn) + ' as TestCode'+rn
                    FROM
                    (
                      select cast(row_number() over(partition by s.ident order by p.prgc) as varchar(50)) rn
                      FROM student s
                      LEFT OUTER JOIN proghist p
                        on s.ident = p.ident
                    ) src
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT Ident, ' + @colsPivot + ' from 
             (
               SELECT  s.ident AS Ident,
                p.prgc AS TestCode,
                row_number() over(partition by s.ident order by p.prgc) rn
              FROM student s
              LEFT OUTER JOIN proghist p
                on s.ident = p.ident
            ) src
            pivot 
            (
                max(TestCode)
                for rn in (' + @cols + ')
            ) p '

execute(@query)

请参阅带有演示的 SQL Fiddle

如果您无权访问该PIVOT函数,则可以使用带有CASE语句的聚合函数:

select ident,
  max(case when rn = 1 then testcode else '' end) TestCode1,
  max(case when rn = 2 then testcode else '' end) TestCode2
from
(
  SELECT  s.ident AS Ident,
    p.prgc AS TestCode,
    row_number() over(partition by s.ident order by p.prgc) rn
  FROM student s
  LEFT OUTER JOIN proghist p
    on s.ident = p.ident
) src
group by ident

请参阅带有演示的 SQL Fiddle

这三个都将产生相同的结果:

|  IDENT | TESTCODE1 | TESTCODE2 |
----------------------------------
| 122222 |         1 |         0 |
| 123456 |         1 |         4 |
| 654321 |         2 |         6 |
于 2012-11-26T19:47:01.273 回答