2013-03-23 31 views
0

這裏是我的PIVOT查詢:與日期或日期時間列使用PIVOT值

select * from t_interview_data 
pivot (avg (widgets) for 
datestamp in ([2009-11-01],[2009-11-02],[2009-11-03],[2009-11-04],[2009-11-05],[2009-11-06],[2009-   11-07] 
,[2009-11-08],[2009-11-09],[2009-11-10],[2009-11-11],[2009-11-12],[2009-11-13],[2009-11-14],[2009- 11-15] 
,[2009-11-16],[2009-11-17],[2009-11-18],[2009-11-19],[2009-11-20],[2009-11-21],[2009-11-22],[2009-11-23] 
,[2009-11-24],[2009-11-25],[2009-11-26],[2009-11-27],[2009-11-28],[2009-11-29],[2009-11-30],[2009-12-01] 
,[2009-12-02])) as AvgWidgetsPerDayPerEmp 

我的問題是:雖然這個查詢的工作,有沒有更容易,更簡單,更優雅寫這樣?

輸出示例:

+0

您可以發佈一些示例數據和預期輸出嗎? – Rachcha 2013-03-23 04:39:01

回答

1

您可以構建查詢和執行。請檢查:

DECLARE @startdt DATETIME, @enddt DATETIME, @QueryCol NVARCHAR(MAX) 

SET @startdt = '2009-11-01' 
SET @enddt = '2009-12-02' 

WHILE @startdt <= @enddt 
BEGIN 
    SET @QueryCol=isnull(@QueryCol, '')+QUOTENAME(convert(nvarchar(20), @startdt, 101))+(CASE WHEN @startdt<>@enddt THEN ',' ELSE '' END) 
    SET @startdt = @startdt + 1 
END 

if(ISNULL(@QueryCol, '')<>'') 
begin 
    set @QueryCol='select * from t_interview_data 
        pivot (avg (widgets) for 
        datestamp in ('[email protected]+')) as AvgWidgetsPerDayPerEmp' 

    exec (@QueryCol) 
end 
+0

我在MS SQL Server 2008中運行了您的查詢,並且出現此錯誤:Msg 8114,Level 16,State 1,Line 3 將數據類型nvarchar轉換爲datetime時出錯。 Msg 473,Level 16,State 1,Line 3 錯誤的值「13-11-2009」在PIVOT運算符中提供。 – 2013-03-23 20:06:14

+0

可能是日期時間格式錯誤...試着格式101,我已經編輯了答案。 – TechDo 2013-03-25 04:08:12

+0

工作,謝謝! – 2013-03-26 01:25:53

相關問題