Question : Left Join with top

I am trying to left join the first record in the event table and match it to the order table. I only want 1 record, but it is showing 2 because there are 2 in the event table. Can someone tell me what I am doing wrong please?

result

ord_hdrnumber      ord_carrier            evt_carrier
49446                               NULL            NE08
49446                               NULL            NE08
1:
2:
3:
4:
5:
select o.ord_hdrnumber, o.ord_carrier, e.evt_carrier
from orderheader o 
left join event e on e.ord_hdrnumber = 
	(select top 1 c1.ord_hdrnumber from event c1 where o.ord_hdrnumber = c1.ord_hdrnumber)
where o.ord_hdrnumber = 49446

Answer : Left Join with top

sorry, outer apply not left apply

select o.ord_hdrnumber, o.ord_carrier, e.evt_carrier
from orderheader o
outer apply (select top 1 * from event e where o.ord_hdrnumber = e.ord_hdrnumber) e
where o.ord_hdrnumber = 49446

In your original query,

(select top 1 c1.ord_hdrnumber from event c1 where o.ord_hdrnumber = c1.ord_hdrnumber)

is guaranteed to return "o.ord_hdrnumber" whenever it matches, which means the query becomes

left join event e on e.ord_hdrnumber = >> o.ord_hdrnumber <<

So you still get multiples.  If you had a unique key in event, you should write it as

left join event e on e.uniqueid =
      (select top 1 c1.uniqueid from event c1 where o.ord_hdrnumber = c1.ord_hdrnumber)

But even that does not work, because in a JOIN, you cannot reference the other tables (i.e. c1).  APPLY can.
Random Solutions  
 
programming4us programming4us