我正在建立一个查询,我将需要在动态列上使用UNPIVOT。 (abcd是示例字符串名称)
data1 data2 com fr random
1 2 a d sq
3 4 b a fd
像这样的UNPIVOT:
data1 data2 Name Website random
1 2 a com sq
1 2 d fr sq
3 4 b com fd
3 4 a fr fd
这里的问题是建立我的第一个表,由于该列,我使用动态SQL(@QueryFinal)。 这是我的UNPIVOT动态查询
'SELECT data1, data2, Name, Website
FROM '+@QueryFinal+'
UNPIVOT (
Name FOR Website in ('+@WebsiteCol+')
) f;'
在我的@QueryFinal中,我有一个WHERE .... ORDER BY,看来UNPIVOT无法处理它。 当我删除WHERE和ORDER BY子句时,出现错误:
Incorrect syntax near the keyword 'UNPIVOT'.
答案 0 :(得分:2)
尝试以下动态枢轴:
--drop table if exists unpivottest
create table unpivotTest (data1 int, data2 int, com char(1), fr char(1))
insert into unpivotTest
select 1, 2, 'a' , 'd' union all
select 3, 4, 'b', 'a'
select * from unpivotTest
declare @colsunpivot as nvarchar(max),
@query as nvarchar(max)
select @colsunpivot = stuff((select ','+ quotename(c.name)
from sys.columns c
where c.object_id = object_id('dbo.unpivottest') and c.name not like '%data%'
for xml path('')), 1, 1, '')
set @query
= 'select data1, data2, name, website
from unpivottest
-- you cannot do the ordering here
unpivot
(
name
for website in ('+ @colsunpivot +')
) u
where data1 = 1 -- here you can use your where clause
order by data1' -- here you can do the ordering by any col
--print @query
exec sp_executesql @query;
查看有效的演示here。
答案 1 :(得分:0)
即使列名与示例中的名称不同,这里也是最终的Query构建,感谢您的帮助。我将WHERE子句放在第一个SELECT中,将ORDER BY放在UNPIVOT中
DECLARE @QueryFinal VARCHAR(max) = @Query + @QueryBis + '
from #CALENDAR_FINAL temp
LEFT JOIN #BURSTS b on b.bur_id = temp.bur_id
LEFT JOIN digital_calendar_status dcs ON dcs.dcs_date = temp.[Date] AND dcs.dif_id = '+convert(varchar(2),@FormatId)+'
LEFT JOIN digital_calendar_event dce ON dce.dce_date = temp.[Date]
WHERE '+@ConditionConflict+@ConditionIcon+@ConditionDate
DECLARE @Pivot VARCHAR(2000)='
SELECT
DateStr, f.Conflict, f.dcs_id, f.Status, f.Website, f.Advertiser, f.Comment, f.EventName, f.EventIcone
FROM ('+@QueryFinal+') AS a
UNPIVOT
(
Advertiser
FOR Website IN ('+@WebsiteCol+')
) f
ORDER BY Date;
'