为什么我不能从外部查询中的子查询中访问定义为“Select 1”的字段?

时间:2017-10-20 15:19:27

标签: sql sql-server tsql subquery sql-server-2014

我有这个子查询:

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告诉我它是一个无效字段。我错过了什么?

1 个答案:

答案 0 :(得分:1)

un001没有exist该字段属于un002子查询。

你还有一个GROUP BYON,所以那里有一些代码丢失。

您应该简化代码并使用CTE使其易于阅读和调试。

这样的事情:

WITH un001 as ( SELECT ... ), 
un002 as ( SELECT ...)
SELECT *
FROM un001 
JOIN un002
  ON un001 .CCaseID = un002.CCaseID