这是我的数据库结构:
我想显示如下数据:
我该怎么做 ?我应该使用枢轴吗?
你可以用PIVOT
这个。使用 PIVOT 有两种方法可以做到这一点,一种是您对要转换的列进行编码的静态 Pivot,另一种是在执行时确定列的动态 Pivot。
静态枢轴:
select *
from
(
select dt, username, product,
'product'
+ cast(row_number()
over(partition by username order by product) as varchar(10)) productNum
from yourtable
) x
pivot
(
min(product)
for productNum in ([product1], [product2], [product3])
) p
order by dt
动态枢轴:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols =
STUFF((SELECT distinct ',' + Quotename('product'
+ cast(row_number()
over(partition by username order by product) as varchar(10)))
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'SELECT dt, username,' + @cols + ' from
(
select dt, username, product,
''product''
+ cast(row_number()
over(partition by username order by product) as varchar(10)) productNum
from yourtable
) x
pivot
(
min(product)
for productNum in (' + @cols + ')
) p
order by dt'
execute(@query)
是的,您应该使用枢轴。
但是,除非您知道会有多少产品,否则您将需要使用动态支点——像这样。