SQL按两行分组?

时间:2016-02-08 12:03:59

标签: sql sql-order-by

我需要对下表进行SQL查询

ID    Name      type     priority
1    French     New       2
2    English    New       3
3    Spanish    New       4
4    Deutch     Old       1
5    Japanese   Old       2
6    Chinese    New       5
7    Monotype   Old       3
8    Hindi      New       6
9    Greek      Old       4

我尝试了ORDER BY type priority ,返回的输出如下所示:

ID      Name     type     priority
1    French     New       2
2    English    New       3
3    Spanish    New       4
6    Chinese    New       5
8    Hindi      New       6
4    Deutch     Old       1
5    Japanese   Old       2
7    Monotype   Old       3
9    Greek      Old       4

我需要像

这样的输出
ID      Name     type     priority
1      French    New      2
4      Deutch    Old      1

有人可以为此建议SQL查询吗?

3 个答案:

答案 0 :(得分:1)

select t.* from table t
  inner join
      (select type, priority from table
       group by  type, priority 
       having priority = MIN(priority)) t2
   on t.type = t2.type and t.priority = t2.priority

答案 1 :(得分:1)

master

我知道,应该给你你正在寻找的东西

答案 2 :(得分:0)

执行此操作的常规方法是使用ANSI标准窗口函数ROW_NUMBER()

select t.*
from (select t.*,
             row_number() over (partition by type order by priority) as seqnum
      from t
     ) t
where seqnum = 1
order by id;