首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > oracle >

只用SQL 能实现这个查询吗

2013-07-08 
求助 只用SQL 能实现这个查询吗idtimecode10703a10702a10701b10630a20703a20702a20701a20630b20629b20628c

求助 只用SQL 能实现这个查询吗
id        time       code
1         0703        a
1         0702        a
1         0701        b
1         0630        a
2         0703        a
2         0702        a
2         0701        a
2         0630        b
2         0629        b
2         0628        c

.....
有上述表格,要求查询结果是

id        time       code
1         0703        a
1         0701        b
1         0630        a
2         0703        a
2         0630        b
2         0628        c
就是order by id, time. 如果是连续code相同的取time最大的那一行,
其他的都不要。能在一个sql里查询出来吗?
[解决办法]

select t.id,t.time.t.code from
(selet id,time,code,row_number() over(partition by id,code order by time desc) rn
from tab_name) t
 where t.rn=1;
------解决方案--------------------



with tb as(
select 1 as id,'0703' as time,'a' as code from dual union all
select 1,'0702','a' from dual union all
select 1,'0701','b' from dual union all
select 1,'0630','a' from dual union all
select 2,'0703','a' from dual union all
select 2,'0702','a' from dual union all
select 2,'0701','a' from dual union all
select 2,'0630','b' from dual union all
select 2,'0629','b' from dual union all
select 2,'0628','c' from dual)
select id,time,code from(
select id,time,code,(select min(time) from tb where a.id=id and a.time<time )a from tb a 
)a
 where nvl((select code from tb where id=a.id and a=time),'$')!=code

热点排行