我需要对动态查询的输出进行排序,将列转换为行,以确保在没有值的行之前只生成具有值的列。如何强制生成列的顺序,以便第一列是包含特定字段值的列,而那些没有特定字段值的列是在我的行尾生成的?
insert into #PriceSheet
select ID, ProductID,SheetNumber ,SheetDesc ,MfgPriceCode,PriceZone
FROM ProductPrice
left join UNITS On SUOM = UOMID
select @colsUnpivot = stuff((select ','+quotename(C.name)
from tempdb.sys.columns as C
where C.object_id = object_id('tempdb..#PricingSheet') and
C.name LIKE '%%'
for xml path('')), 1, 1, '')
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 #PriceSheet
) t
cross apply
tempdb.sys.columns as C
where C.object_id = object_id('tempdb..#PricingSheet')
and C.name Not in ('CreateDate', 'LastModifiedDate')
group by c.name, t.rn
order by t.rn
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'select *
from
(
select ProductID, col + cast(rn as varchar(10)) new_col, val
from
(
select
cast(ProductID as varchar(50))ProductID
,cast(SheetNumber as varchar(50))SheetNumber
,cast(SheetDesc as varchar(50))SheetDesc
,cast(MfgPriceCode as varchar(50))MfgPriceCode
,cast(PriceZone as varchar(50))PriceZone
row_number() over(partition by productid order by productid) rn
from #PriceSheet
) x
unpivot
(
val
for col in ('+ @colsunpivot +')
) u
) x1
pivot
(
max(val)
for new_col in
('+ @colspivot +')
) p'
比如说,首先为 SheetNumber 不等于 NULL 的行生成列,然后再为 NULLS 生成列。