sql server - In sql, can you join to a select statement that references the outer tables in other joins? -
what want transform following sql
select x y left join z on y.id=z.id y.fld='p'
into
select y y left join (select top 1 id z z.id=y.id order z.primarykey desc) on 1=1 y.fld='p'
the reason want because z has multiple rows can joined y, not unique in distinguishable way, other 1 need latest one, , need 1 record. possible? tried mssql complained cannot reference y.id within sub query.
how cte approach:
;with cte ( select id, primarykey, row_number() on (partition id, order primarykey desc) rn z ) select x y left join cte on cte.id = y.id cte.rn = 1
Comments
Post a Comment