SQL 列名错误但确实存在

SQL says wrong column name but it does exist

我有这个问题

declare @department_code varchar(8), @basedate varchar(8);
set @department_code = 'A';
set @basedate = '20200501';

Create table #DEPARTMENT_MT(DEPARTMENT_CODE varchar(8), REVISION_DATE varchar(8), PARENT_DEPARTMENT_CODE varchar(8), DEL_FLG bit);

insert into #DEPARTMENT_MT values('A', '20200101',  'X', 0);
insert into #DEPARTMENT_MT values('A', '20220101',  '', 0);

insert into #DEPARTMENT_MT values('B', '20200101', 'A', 0);
insert into #DEPARTMENT_MT values('B', '20220101', '', 0);

insert into #DEPARTMENT_MT values('C', '20200101', 'B', 0);
insert into #DEPARTMENT_MT values('C', '20220101', 'A', 0);

insert into #DEPARTMENT_MT values('D', '20200101', 'C', 0);
insert into #DEPARTMENT_MT values('D', '20220101', 'F', 0);


insert into #DEPARTMENT_MT values('E', '20200101', 'D', 0);
insert into #DEPARTMENT_MT values('F', '20200101', 'E', 0);
insert into #DEPARTMENT_MT values('G', '20200101', 'F', 0);
insert into #DEPARTMENT_MT values('H', '20200101', 'G', 0);

;with cte as 
(
    select *, cast(0 as bigint) as seqnum   from #DEPARTMENT_MT where DEPARTMENT_CODE=@department_code and REVISION_DATE = (select max(REVISION_DATE) from #DEPARTMENT_MT where REVISION_DATE < @basedate and DEPARTMENT_CODE=@department_code)
    union all
    select t.*, row_number() over (partition by t.DEPARTMENT_CODE, t.REVISION_DATE order by t.REVISION_DATE desc) as seqnum1
        from  #DEPARTMENT_MT t
        inner join cte on cte.DEPARTMENT_CODE = t.PARENT_DEPARTMENT_CODE AND t.REVISION_DATE <= cte.REVISION_DATE 
        where seqnum1 = 1
)

select * from cte;

我想做的是在递归部分只获取 have row_number = 1 的行

select t.*, row_number() over (partition by t.DEPARTMENT_CODE, t.REVISION_DATE order by t.REVISION_DATE desc) as seqnum1
    from  #DEPARTMENT_MT t
    inner join cte on cte.DEPARTMENT_CODE = t.PARENT_DEPARTMENT_CODE AND t.REVISION_DATE <= cte.REVISION_DATE 
    where seqnum1 = 1

我收到这个错误:

Invalid column name 'seqnum1'.

如果我将列名从 seqnum1 更改为 seqnum,它不会产生错误,但结果与我预期的不同

为什么在where条件中使用seqnum1会出现上述错误? (如果我不包含where条件,就不会报错)

seqnum1 不存在于 #DEPARTMENT_MT 中,如果您将其包装起来,它就会起作用,例如 select * from ( 您的查询 ) as q where q.seqnum1=1