我遇到的问题是表格中有多个结果用于我想要查找的内容。如果我有这个:
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
答案 0 :(得分: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
,那么您可以对这些值进行硬编码:
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)
数据:
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
语句的聚合函数:
| IDENT | TESTCODE1 | TESTCODE2 |
----------------------------------
| 122222 | 1 | 0 |
| 123456 | 1 | 4 |
| 654321 | 2 | 6 |
这三个都会产生相同的结果:
{{1}}