可能重复:
Poor Man’s SQL Pivot. List Questions as Columns and Answers per User in one row
我有以下查询首先为每个外键提取12条记录(在缺少记录的情况下为空值),然后将每个外键的所有12条记录转换为一列。但是,下面的代码会生成12行,但无法将所有行转换为列。相反,它只对我的一个外键IDS进行转换,然后停止。
请帮我正确转动,以便每个ProductID都能获得一行。提前谢谢。
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX)
--BEGIN TRY
IF EXISTS
(
SELECT *
FROM tempdb.dbo.sysobjects
WHERE ID = OBJECT_ID(N'tempdb..#ManufacturerAttributes')
)
BEGIN
DROP TABLE #ManufacturerAttributes
END
Create table #ManufacturerAttributes
(
ProductID uniqueIdentifier,
PAID uniqueidentifier,
MfgAttrLabel varchar(50),
MfgAttrVal varchar(3072),
MfgAttrUOM varchar(50),
rowindex int
)
;With Number
As
(
Select 1 as rownum union all Select 2 union all Select 3 union all Select 4 union all Select 5 union all Select 6 union all Select 7 union all Select 8 union all Select 9 union all Select 10 union all Select 11 union all Select 12
),
ProductDetail
as
(
select P.ProdID, N.rownum from IDWProduct P cross join Number N
)
Insert into #ManufacturerAttributes
Select ProdID , PAVAttributeID,PANAme, PAVValue, UOMLabel, P.rownum
from ProductDetail P
Left join (select Pr.*, row_number() over (partition by PAVProductID order by PAVID) as Rn from IDWProductAttributeValues Pr ) Pr ON rownum = Pr.Rn And PAVProductID = ProdID
left join IDWUnitofMeasures on Pr.PAVUOM = UOMID
left join IDWAttributes A on Pr.PAVAttributeID = A.PAID AND A.PAIsManufacturerSpecific = 1
Select * from #ManufacturerAttributes
select @colsUnpivot = stuff((select ','+quotename(C.name)
from tempdb.sys.columns as C
where C.object_id = object_id('tempdb..#ManufacturerAttributes')
for xml path('')), 1, 1, '')
-- select @colsUnpivot
select @colsPivot = STUFF((SELECT ',' + quotename(c.name + cast(t.rn as varchar(10)))
from
(
select row_number() over(partition by ProductID order by ProductID) rn from #ManufacturerAttributes
) t
cross apply
tempdb.sys.columns as C
where C.object_id = object_id('tempdb..#ManufacturerAttributes')
group by c.name, t.rn
order by t.rn
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--select @colsPivot
set @query
='select *
from
(
select ProductID, PAID, RowIndex,
col + cast(rn as varchar(10)) new_col,
val
from
(
select
Cast (ProductID as NVarchar(3072)) ProductID
,Cast(PAID as NVarchar(3072)) PAID
,Cast (MfgAttrLabel as NVarchar(3072)) MfgAttrLabel
,Cast (MfgAttrVal as NVarchar(3072)) MfgAttrVal
,Cast (MfgAttrUOM as NVarchar(3072)) MfgAttrUOM
,Cast(rowindex as NVarchar(3072)) rowindex
,row_number() over(partition by ProductID order by ProductID) rn
from #ManufacturerAttributes
) x
unpivot
(
val
for col in ('+ @colsunpivot +')
) u
) x1
pivot
(
max(val)
for new_col in
('+ @colspivot +')
) p'
-- Print @query
exec(@query)