是动态数据透视中的任何其他方式

时间:2015-07-20 05:56:00

标签: sql sql-server

在回答一个问题的同时,我还记得其他问题。当它是正常的支点时它工作正常但是如果我在问题出现时尝试进行动态查询

回答之后他要求动态Pivot

PIVOT the date column in SQL Server 2012

if OBJECT_ID('tempdb..#temp') is not null
begin
drop table #temp
end


CREATE  table #temp (dated varchar(10),E1 int,E2 int,E3 int,E4 int)
insert into #temp
(dated,E1,E2,E3,E4)values 
('05-27-15',1,1,2,3),
('05-28-15',2,3,NULL,5),
('05-29-15',3,4,null,2)

DECLARE @statement NVARCHAR(max)
,@columns NVARCHAR(max)

SELECT @columns = ISNULL(@columns + ', ', '') + N'[' + tbl.dated + ']'
FROM (
   SELECT DISTINCT dated
   FROM #temp
   ) AS tbl


SELECT @statement = 'Select P.col,MAX('+@columns+') from ( 
select col,' + @columns + ' from (
select * from #temp
CROSS APPLY(values(''E1'',E1),(''E2'',E2),(''E3'',E3),(''E4'',E4))cs (col,val))PP
PIVOT(MAX(val) for dated IN  (' + @columns + ')) as PVT)P
GROUP BY P.COL
'
PRINT @statement
EXEC sp_executesql @statement = @statement

我的问题是如何动态地为所有日期采用MAX()条件 最大(05-27-15),最大(05-28-15)等日期动态如何分配最大条件

1 个答案:

答案 0 :(得分:0)

MAX聚合移动到列列表variable将解决问题

DECLARE @statement      NVARCHAR(max),
        @columns        NVARCHAR(max),
        @select_columns NVARCHAR(max)

SELECT @select_columns = Isnull(@select_columns + ', ', '')+ N'MAX([' + tbl.dated + '])'
FROM   (SELECT DISTINCT dated
        FROM   #temp) AS tbl

SELECT @columns = Isnull(@columns + ', ', '') + N'[' + tbl.dated+ ']'
FROM   (SELECT DISTINCT dated
        FROM   #temp) AS tbl

SELECT @statement = 'Select P.col,' + @select_columns
                    + ' from ( 
    select col,' + @columns
                    + ' from (
    select * from #temp
    CROSS APPLY(values(''E1'',E1),(''E2'',E2),(''E3'',E3),(''E4'',E4))cs (col,val))PP
    PIVOT(MAX(val) for dated IN  (' + @columns
                    + ')) as PVT)P
    GROUP BY P.COL
' 


PRINT @statement
EXEC sp_executesql @statement = @statement
相关问题