sql server - SQL - SELECT rows conditionally -
the following criteria select rows:
- for same sysid, p2 preferred p1.
i came logic
declare @products table ( id int, sysid varchar(100) ); insert @products select id, sysid productmain productcode = 'p2' insert @products select id, sysid productmain productcode = 'p1' , sysid not in (select sysid @subscription) --result select id,sysid @products
sample data
id sysid productcode 1 121 p1 2 121 p2 3 122 p1 4 123 p2 5 124 p1 6 124 p2
desired output
id sysid 2 121 3 122 4 123 6 124
i know there should better logic this. please help. in advance.
if p1, p2 not actual data, change order by
case when productcode = 'p2' 1 else 2 end
select * ( select *, rn = row_number() on (partition sysid order productcode desc) yourtable ) d d.rn = 1
Comments
Post a Comment