列存在时,为什么会出现“列名无效”错误

时间:2018-03-21 17:26:21

标签: sql sql-server join

这是我的代码:

declare @maxsnap table (sita varchar(10), date date, SNAPSHOT_DATE date)

insert into @maxsnap 
   select 
       sita, date, max(SNAPSHOT_DATE) snapshot 
   from 
       [UKRMC].[dbo].[Roll_forecast] 
   where 
       date between '2018-03-21' and '2018-05-31'
   group by 
       sita, date 

select 
    roll.DATE, roll.SITA,
    contacts.rooms,
    roll.SEGMENT, roll.RNS 
from 
    [UKRMC].[dbo].[Roll_forecast] roll
join 
    [UKRMC].[dbo].[Contacts] contacts on contacts.SITA = roll.SITA
join 
    @maxsnap snap on roll.DATE = snap.date 
                  and roll.SITA = snap.sita 
                  and roll.SNAPSHOT_DATE = snap.snapshot
where 
    roll.date between '2018-03-21' and '2018-05-31' 

我得到的错误是

  

无效的列名称'snapshot'

当我加入@maxnsap表变量时。但那个专栏确实存在!

2 个答案:

答案 0 :(得分:1)

你有这个条件:

roll.DATE = snap.date

但是,该列名为snapshot_date

roll.DATE = snap.snapshot_date

答案 1 :(得分:1)

加入错误

     and roll.SNAPSHOT_DATE = snap.SNAPSHOT_DATE