sql server - Top 1 for each joined record -


in sql server query, want return @ 1 lostreason each booking. however, sub-query seems returning first record lostbusiness table every booking. let me know if need clarify.

select             bookings.bookingnumber, lost.lostreason                 bookings      left outer join(select top (1)                         bookingnumber,                         lostreason                                                        lostbusiness) lost on bookings.bookingnumber = lost.bookingnumber 

if need more 1 column

select           bookings.bookingnumber, lost.* bookings     outer apply     (          select top 1             lost.bookingnumber,              lost.lostreason,             --other columns         lostbusiness lost         bookings.bookingnumber = lost.bookingnumber         order -- put order here     ) lost 

or

;with cte (     select               *,         row_number() on (partition bookings.bookingnumber order /* ??? */) row_num     bookings         left outer join lostbusiness lost on bookings.bookingnumber = lost.bookingnumber  )  select * cte row_num = 1 

if need more 1 column

select           bookings.bookingnumber, max(lost.lostreason) lostreason bookings     left outer join lostbusiness lost on bookings.bookingnumber = lost.bookingnumber group bookings.bookingnumber 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -