Oracle分组查询

2019-04-06  本文已影响0人  玩大神的简书

分组查询,且只取每一组内的一条最新的记录

需求:查询 code 为a,b,c且在有效时间段内的每个code最新的一条记录(code不是主键)
select * from (select code
    col1,
    col2,
    row_number() over (partition by code order by time desc) rank
    from t_order
    where type= '107'
    and to_char(sysdate, 'yyyymmdd-hh24:mi:ss') <= validuntilTime
        and code in
    ('a','b','c')
    ) where rank = 1
(select code
    col1,
    col2,
    row_number() over (partition by code order by time desc) rank
    from t_order
    where type= '107'
    and to_char(sysdate, 'yyyymmdd-hh24:mi:ss') <= validuntilTime
        and code in
    ('a','b','c')
    ) 
CODE COL1 COL2 RANK
a xxx xxx 1
a xxx xxx 2
a xxx xxx 3
b xxx xxx 1
b xxx xxx 2
c xxx xxx 1
c xxx xxx 2
c xxx xxx 3
c xxx xxx 4
上一篇 下一篇

猜你喜欢

热点阅读