在构造的字符串查询动态中使用 UNPIVOT

Using UNPIVOT in constructed String Query Dynamic

我正在构建一个查询,我需要在动态列上使用 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

这里的问题是为了构建我的第一个 table 我使用动态 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'.

尝试以下动态枢轴:

--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

即使它与此处示例中的列名不同,也是最终构建的查询,感谢您的帮助。我将 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;
'