2015-07-20 83 views
0

做任何其他方式,同時回答一個問題,我腦海中遇到了其他問題。當它是正常的樞軸它工作正常,但如果我試圖做動態查詢時出現問題是在動態樞軸

回答後,他問動態透視

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('[email protected]+') 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()條件的所有日期動態像 最大(15年5月27日),MAX( 05-28-15)等日期即將到來在聲明的聲明ically如何分配最大條件

回答

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

它顯示語法錯誤 – mohan111

+0

可能是你加最大但它不會在主軸max()條件 – mohan111

+0

@ mohan111 - 更新檢查現在 –