仅考虑db值中的较小数字

时间:2016-12-02 12:34:45

标签: sql

我有一个包含两列的数据库表。一列是id,另一列是序列号。但是,我在id列中有重复的id。无论哪个具有重复的ID,该ID的序列号都将具有序列。就像我有1005次3次,这个序列是0,1和2.下面是我的表的例子。

ID       Sequence
1001     0
1002     0
1003     1
1004     2
1005     0
1005     1
1005     2
1006     4
1006     5
1007     1
1007     2

在我的上表中,重复了1005,1006和1007,它有不同的序列号。

现在,我想从id中省略重复的数字,并且省略重复的id应该具有更高的序列号。

所以,我想要结果如下

ID       Sequence
1001     0
1002     0
1003     1
1004     2
1005     0
1006     4
1007     1

总计数为7行

2 个答案:

答案 0 :(得分:1)

select ID, max(Sequense) as Sequense
from tbl
group by ID

答案 1 :(得分:0)

假设您只需要表中的那两列,通常使用窗口函数来解决这个问题:

select *
from (
  select t.*,
         row_number() over (partition by t.id order by t.sequence) as rn
  from the_table t
) x
where x.rn = 1;