0

This is my code:

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' 

The error I am getting is

Invalid column name 'snapshot'

when I join the @maxnsap table variable. But that column does exist!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sorath
  • 543
  • 3
  • 10
  • 32

2 Answers2

1

You have this condition:

roll.DATE = snap.date

However, the column is called snapshot_date:

roll.DATE = snap.snapshot_date
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

Error in join

     and roll.SNAPSHOT_DATE = snap.SNAPSHOT_DATE
Mazhar
  • 3,797
  • 1
  • 12
  • 29
  • Thank you, this worked! However, I called it 'snapshot' so it doesn't make sense to me why I need to refer to the original column name – Sorath Mar 21 '18 at 17:36
  • 1
    The column in the @maxsnap table is called SNAPSHOT_DATE. In your query to populate the table you've used the alias snapshot but this doesn't change the name of the column in the table – Mazhar Mar 21 '18 at 17:40
  • @Sorath you cannot use the alias name as to the compiler the alias hasn't been assigned yet, if you see [this answer](https://stackoverflow.com/a/3841804/7147233) it explains that each section of the select statement in ran in an order of precedence, stating that the from is done before the select – WhatsThePoint Mar 21 '18 at 17:42
  • That alias only existed for the initial `insert` and even there it was ignored. Since you didn't specify a column list it just assumed the columns in the same order as you created the table. – shawnt00 Mar 21 '18 at 17:47