t-sql中的特定组

t-sql中的特定组,sql,sql-server,tsql,group-by,Sql,Sql Server,Tsql,Group By,是否有人知道如何在T-SQL中获得此示例中的结果: id val1 val2 1. a b 1. c d 1. b a 1. d c 1. e f 2. k m 2. m p 2. m k a b和b a组仅在a b中。对于c、d、c和k、m、m、k,使用带有自定义分区的行编号 我将这样写: select id, val1, val2 from t where val1 < val2 union all select id, val1, va

是否有人知道如何在T-SQL中获得此示例中的结果:

id val1 val2 1. a b 1. c d 1. b a 1. d c 1. e f 2. k m 2. m p 2. m k a b和b a组仅在a b中。对于c、d、c和k、m、m、k,使用带有自定义分区的行编号

我将这样写:

select id, val1, val2
from t
where val1 < val2
union all
select id, val1, val2
from t
where val1 > val2 and
      not exists (select 1 from t t2 where t2.id = t.id and t2.val1 = t.val2 and t2.val2 = t.val1);
select id,val1,val2
from (select id,val1,val2,
      row_number() over(partition by id,case when val1<val2 then val1 else val2 end
                                       ,case when val1>val2 then val1 else val2 end 
                        order by val1) as rnum
      from tbl
     ) t
where rnum=1
select id, val1, val2
from t
where val1 < val2
union all
select id, val1, val2
from t
where val1 > val2 and
      not exists (select 1 from t t2 where t2.id = t.id and t2.val1 = t.val2 and t2.val2 = t.val1);