i have two tables, program and event. what i am trying to do is get the closest upcoming event for each program. there exists the possibility however, that a program might have no events attached to it or only events that happened in the past, but i still need the program to show up with an empty value for the event dates, not just go away. so i began implementing an outer join based on what i had googled and found outer apply.
the problem appears to be that i have no access to any of the columns in event, geting the error 'Invalid column name 'start_date'.' (this happens with all three columns, not just start date)
so i either need to learn why i can’t access those columns, or figure out a new way to go about writing the query that returns all programs as well as joins the events table for nearest event/leaves values empty if nothing exists
SELECT
p.*,
e.type,
e.start_date,
e.end_date
FROM
program p
outer apply (
select top(1) pk_id from events e where fk_program_id = p.pk_id and end_date >= GetDate()
) e
You’re not returning any columns except pk_id from events. Add the other columns to your select statement. 🙂