SQL,按列分组

时间:2014-04-25 14:29:12

标签: sql oracle group-by

我有这样的数据:

 ID              VERSION        SEQUENCE 
 -------------- -------------- ---------------
  01-001         01            001          
  01-002         01            002          
  02-002         02            002

我想为每个序列选择更高版本,以便得到如下结果:

 ID              VERSION        SEQUENCE 
 -------------- -------------- ---------------
  01-001         01            001             
  02-002         02            002

我认为请求应该在序列中包含一个组,但我无法使其工作

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

使用公用表表达式:

with HighestSequence(ID,MaxSequence)
as 
(
   select id, max(Sequence)
   from table
   group by ID
)

select t.*
from table t
inner join HighestSequence hs
on t.id = hs.id
and t.sequence = hs.sequence

答案 1 :(得分:0)

因此请过滤以仅包含 版本中序列中最高版本的行

Select id, version, sequence
From DataTable dt
where version =
    (Select Max(version)
     From DataTable 
     where Sequence = dt.Sequence)

答案 2 :(得分:0)

您没有指定DBMS,因此这是ANSI SQL:

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