Pivot查询出错

时间:2011-07-29 07:26:55

标签: sql sql-server tsql sql-server-2008

我有以下查询

 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 ('+@Days+')) AS pvt'

EXECUTE (@query)

它给了我错误

Incorrect syntax near '('.

2 个答案:

答案 0 :(得分:2)

如果您使用DISTINCT关键字,则无法按SELECT中未指定的字段进行排序。一个不同的值可能有多个值来排序,因此可能没有正确的顺序。

Blog entry关于错误。

答案 1 :(得分: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 ('+@Days+')) AS pvt'

EXECUTE (@query)