我有这个子查询:
LEFT JOIN (SELECT 1 as exist
, MAX (ev.EventDate) as eventdate
, evt.EventCode
, CCaseID
FROM stg.Event ev
JOIN stg.EventTemplate evt
ON ev.EventTemplateID = evt.ID
WHERE evt.EventCode = 'UN002'
Group by CCaseID, evt.EventCode) as un002
ON un002.CCaseID = ev.CCaseID
WHERE evt.EventCode = 'UN001'
AND (un002.eventdate < ev.eventdate OR un002.eventdate IS NULL)
Group by ev.CCaseID, evt.EventCode) as un001
ON cc.ID = un001.CCaseID
我现在尝试按un001.exist
访问外部查询中的exists字段,但SQL Server告诉我它是一个无效字段。我错过了什么?
答案 0 :(得分:1)
un001
没有exist
该字段属于un002
子查询。
你还有一个GROUP BY
和ON
,所以那里有一些代码丢失。
您应该简化代码并使用CTE使其易于阅读和调试。
这样的事情:
WITH un001 as ( SELECT ... ),
un002 as ( SELECT ...)
SELECT *
FROM un001
JOIN un002
ON un001 .CCaseID = un002.CCaseID