在构建查询字符串动态使用UNPIVOT

问题描述 投票:2回答:2

我建立一个查询,我需要动态列的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'.
sql-server dynamic unpivot
2个回答
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


0
投票

即使是不相同的列名在这里的例子是帮助最终查询内置感谢。我把第一个SELECT的WHERE子句和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;
'
© www.soinside.com 2019 - 2024. All rights reserved.