2011-07-29 85 views
1

我有以下查詢錯誤樞軸查詢

DECLARE @query NVARCHAR(4000) 
DECLARE @Days NVARCHAR(4000) 
SELECT @Days = STUFF((SELECT DISTINCT 
         '],[' + ltrim(str(datepart(dw,visitdate))) 
         FROM mktPlanHospitals 
         ORDER BY '],[' + ltrim(str(datepart(dw,visitdate))) 
         FOR XML PATH('')      ), 1, 2, '') + ']' 

SET @query = 
'SELECT * FROM 
(
    SELECT DoctorID,datepart(dw,visitdate),DoctorID 
    FROM mktPlanHospitals 
)t 
PIVOT (SUM(DoctorID) FOR datepart(dw,visitdate) 
IN ('[email protected]+')) AS pvt' 

EXECUTE (@query) 

這是給我的錯誤

Incorrect syntax near '('. 

回答

2

你不能在你的SELECT不指定字段順序,如果你使用的DISTINCT關鍵詞。一個不同的值可以有幾個值來排序,因此可能沒有正確的順序。

Blog entry關於錯誤。

+0

我下面從http://dotnetgalactics.wordpress.com/2009/10/23/using-sql-server-20052008-pivot後的問題-on-未知數柱動態樞軸的。我怎麼能修改得到resut – Tassadaque

+0

我會刪除ORDER BY中的YEAR()函數,我不認爲這需要在那裏。 – Jacob

+0

感謝您的回覆。我更新了查詢並獲得錯誤的語法錯誤。請參閱更新的問題 – Tassadaque

1

這裏是工作查詢解決

DECLARE @query NVARCHAR(4000) 
DECLARE @Days NVARCHAR(4000) 
SELECT @Days = STUFF((SELECT DISTINCT 
         '],[' + ltrim(str(datepart(dw,visitdate))) 
         FROM mktPlanHospitals 
         ORDER BY '],[' + ltrim(str(datepart(dw,visitdate))) 
         FOR XML PATH('')      ), 1, 2, '') + ']' 

SET @query = 
'SELECT * FROM 
(
    SELECT DoctorID,datepart(dw,VisitDate) as vdate 
    FROM mktPlanHospitals 
)t 

PIVOT (SUM(DoctorID) FOR vdate 
IN ('[email protected]+')) AS pvt' 

EXECUTE (@query)