我正在尝试完成一个SQL语句,我在其中使用With Clause构建查询,然后围绕工作周数字进行透视。工作周基于接下来的10个工作周和之前的10个工作周.WIL子句可以完美地构建初始查询。但是,我无法从CTE2别名中选择动态列。
有什么想法吗?
declare @thisDate Date = '20151110';
DECLARE @DateFrom DATE = DateAdd(week,-10,@thisDate) ;
DECLARE @DateTo DATE = DateAdd(week,10,@thisDate) ;
WITH T(date) AS
(SELECT @DateFrom
UNION all
SELECT DateAdd(week,1,T.date) FROM T WHERE T.date < @DateTo
)
,
CTE (proID,ms,ww) as
(select proID,max(mtypid) as ms, DatePart(week,MeetDate) as ww from tblMinMeeting where proID in(723,837) and MTYPID in(1,2,3,4) group by proid, DatePart(week,MeetDate)
union
select proID,9,DatePart(week,DesignStart) from tblProjects
union
select proID,7,DatePart(week,DesignFinish) from tblProjects
),
CTE2 (proID,ww,ms)
as
(
select CTE.proID, ww,mt.Name from T join
CTE on datepart(week,T.date) = CTE.ww left outer join
(select MTYPID,Name from tblMinMeetType) mt on CTE.ms = mt.MTYPID
)
SELECT *
FROM (
select proID,ww,ms
FROM CTE2) as s
PIVOT
(MAX(MS) for ww IN(select STUFF((SELECT DISTINCT ',' + QUOTENAME(CONVERT(VARCHAR,ww),'')
FROM CTE2
FOR XML PATH('')),1,1,''))) as PVTTable
使用SELECT STUFF
时,查询无法识别CTE2别名这是错误
Msg 156, Level 15, State 1, Line 42
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 44
Incorrect syntax near ')'.