这种数据转换称为 aPIVOT
并且从 SQL Server 2005 开始,有一个函数可以将数据从行转换为列。
有几种方法可以做到这一点,具体取决于您是否有静态数量的值要转置到列中。所有这些都涉及向row_number()
数据添加 a,以便您可以返回任何产品的多行。
您可以将聚合函数与CASE
表达式一起使用:
select
max(case when product = 'x' then detail end) x,
max(case when product = 'y' then detail end) y,
max(case when product = 'z' then detail end) z
from
(
select p.product, d.detail,
row_number() over(partition by p.product order by p.slno) rn
from product p
inner join detail d
on p.product = d.product
) src
group by rn
请参阅带有演示的 SQL Fiddle
您可以使用以下PIVOT
功能:
select x, y, z
from
(
select p.product, d.detail,
row_number() over(partition by p.product order by p.slno) rn
from product p
inner join detail d
on p.product = d.product
) src
pivot
(
max(detail)
for product in (x, y, z)
) piv
请参阅SQL Fiddle with Demo。
如果您有未知数量的值(在这种情况下为产品)转换为列,那么您将需要使用动态 SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(product)
from product
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + ' from
(
select p.product, d.detail,
row_number() over(partition by p.product order by p.slno) rn
from product p
inner join detail d
on p.product = d.product
) x
pivot
(
max(detail)
for product in (' + @cols + ')
) p '
execute(@query)
请参阅带有演示的 SQL Fiddle
所有查询的结果是:
| X | Y | Z |
--------------------------
| good | bad | worse |
| bad | (null) | (null) |