查询 cte - 无法绑定多部分标识符。如何解决此问题以便我可以查询 table? SQL 会计背景的新手

Querying a cte - The multi-part identifier could not be bound. How do I fix this so I can query the table? New to SQL accounting background

我正在尝试提取连接 3 tables

的数据集

在数据集中,对于 AB.AbsenceTypesUID 的每个 AB.EmployeeUID,我需要来自 AB.BalanceTime 的最新记录。

数据集与我需要的输出是正确的,在我查询 CTE 时它失败了。

;WITH cte AS
(
    SELECT TOP (1000) 
        AB.[UID],
        AB.BalanceTime,
        AB.AbsenceTypesUID,
        AB.Mins,
        E.FullName,
        E.FirstName, E.LastName,
        AB.EmployeeUID,
        AT.LongName,
        ROW_NUMBER() OVER(PARTITION BY AB.[UID], AB.EmployeeUID ORDER BY AB.BalanceTime DESC) AS RUN
    FROM 
        [RiteqDB].[dbo].[AbsenceBalance] AB
    LEFT JOIN 
        [RiteqDB].[dbo].Employee E ON AB.EmployeeUID = E.UID
    LEFT JOIN 
        [RiteqDB].[dbo].AbsenceTypes AT ON AB.AbsenceTypesUID = AT.UID
)
SELECT * 
FROM cte
WHERE RUN = 1 AND E.FullName = 'john citizen'

错误

Msg 4104, Level 16, State 1, Line 45
The multi-part identifier "E.FullName" could not be bound.

我用谷歌搜索了这个问题,根据我的理解,加入的 tables 不与 CTE 交互,这就是它失败并出现以下情况的原因。

AND E.FullName = 'john citizen'     

如何更改脚本以便查询 table?

Table 别名 E 仅在 inside CTE 中定义,不在外部查询中定义。在该范围内,只有一个(派生的)table,称为 cte,并且具有 CTE returns.

的所有列名

换句话说,你可以这样做:

with cte as (...)
select * 
from cte
where run = 1 and fullname = 'john citizen'

如果你真的想使用别名,那么给CTE起个别名,然后:

with cte as (...)
select c.* 
from cte c
where c.run = 1 and c.fullname = 'john citizen'