I should be able to reference tables in the join clauses from a subquery, shouldn't I?
But the following query is giving me errors saying they can't be bound:
select *
from call c
JOIN call_task ct ON c.call_no=ct.call_no AND ct.calltask_no = (select min(ict.calltask_no) FROM call_task ict WHERE ict.call_no=c.call_no)
JOIN business b ON c.service_business_id=b.business_id
JOIN item i ON ct.item_id=i.item_id
JOIN ( select top 1 *
FROM contract_line icl
WHERE icl.item_id = i.item_id
AND icl.location_no = c.service_location_no
AND icl.business_id = b.business_id
ORDER BY icl.cancel_date asc
) cl ON i.item_id=cl.item_id
AND cl.location_no=c.service_location_no
AND cl.business_id=b.business_id
JOIN [contract] co ON cl.cont_no=co.cont_no
JOIN business_location bl ON bl.business_id=c.service_business_id AND bl.location_no=c.service_location_no
WHERE b.bus_code='INGRAM04'
AND ct.cont_no is null
AND call_sts NOT IN ('BB', 'BI', 'CA', 'CL', 'IP')
--AND cl.end_date > c.entry_date
ORDER BY c.create_time
The errors are: Msg 4104, Level 16, State 1, Line 1 The multi-part identifier "i.item_id" could not be bound. Msg 4104, Level 16, State 1, Line 1 The multi-part identifier "c.service_location_no" could not be bound. Msg 4104, Level 16, State 1, Line 1 The multi-part identifier "b.business_id" could not be bound.
I don't understand why I'm getting these errors, and can't think of any way around it. The item_no on a contract_line can appear more than once on a contract, if it was canceled and a new line created for instance. In those cases I need to ignore the cancelled line and pull the current one. Doing the subquery and ordering by cancel_date pulls the nulls first so it accomplishes what I want... but this weird binding error is screwing me up. I know I've used this technique before so now I'm confused...