我正在使用SQL Server 2014,我在下面的SQL查询时遇到问题。似乎某处存在语法错误,但我找不到它。
我正在加入来自两个不同视图的两个选择查询,即ReservationList
和ARACCOUNT
。
USE MyDatabase
;WITH q1 AS (
select *
from ReservationList
WHERE [Market Segment Code] <> 'COMP' AND
NOT (Status] = 'CANCELED' OR [Status] = 'NOSHOW' OR [Status] = 'WAITLIST') AND
NOT [Departure Date] < '2014-07-01' AND
NOT [Market Segment Code] = 'COMP' AND
NOT [Arrival Date] = [Departure Date]
)a
q2 AS (
SELECT
[PMSConfirmationNumber],
[FOC ACCOUNT],
[AR ACCOUNT NAME]
FROM
ARACCOUNT
)b
Select
q1.*
from
q1
JOIN q2 ON q1.PmsConfirmatioNnumber = q2.foh_PmsConfirmationNumber
错误消息如下:
Msg 102, Level 15, State 1, Line 21
Incorrect syntax near 'a'.
Msg 102, Level 15, State 1, Line 29
Incorrect syntax near ')'.
我还需要从ARACCOUNT中选择的字段出现在最终输出中。如何修改我的查询以包含我的q2选择?
答案 0 :(得分:5)
你错过了两个CTE之间的逗号。另外,删除别名 - 定义CTE时不需要它们:
;WITH q1 AS (
select *
from ReservationList
WHERE [Market Segment Code] <> 'COMP'
AND NOT ([Status] = 'CANCELED' OR [Status] = 'NOSHOW' OR [Status] = 'WAITLIST')
AND NOT [Departure Date] < '2014-07-01'
AND NOT [Market Segment Code] = 'COMP'
AND NOT [Arrival Date] = [Departure Date]
), -- alias dropped and comma added here
q2 AS (
SELECT [PMSConfirmationNumber],[FOC ACCOUNT],[AR ACCOUNT NAME]
FROM ARACCOUNT
) -- alias dropped
Select q1.*, q2.* from q1
JOIN q2 ON q1.PmsConfirmatioNnumber = q2.foh_PmsConfirmationNumber