如何在oracle中通过sql查询找到每个id的top/max值?

sc4hvdpw  于 2021-07-27  发布在  Java
关注(0)|答案(4)|浏览(314)

如何使用查询来查找每个标识符的最大值(不是唯一的)?我的table:

id      date      repeat_cycle
8    30.07.2020      0
4    28.04.2020      1
4    28.04.2020      0
15   01.01.2020      9
15   24.12.2019      8
15   23.12.2019      7
1    20.12.2019      5
15   19.12.2019      6
1    19.12.2019      4

我想要每个id的最大值(重复周期中的最大值)。我的sql查询是错误的,我不知道为什么。有人会建议如何修复它或其他查询。

SELECT * FROM (
        SELECT 
         id,
         date,
         repeat_cycle
        FROM table t1
           order by repeat_cycle desc
        ) t1
and rownum=1;
ovfsdjhp

ovfsdjhp1#

您可以使用分析函数:

select *
from (
    select 
        t.*, 
        row_number() over(partition by id order by repeat_cycle desc) rn
    from mytable t
) t
where rn = 1

或者,如果表中只有三列,则 keep 语法可能合适:

select
    id,
    max(date) keep(dense_rank first order by repeat_cycle desc) date,
    max(repeat_cycle) repeat_cycle
from mytable
nwsw7zdq

nwsw7zdq2#

你可以用 row_number() ,

select id, date, repeat_cycle from
(select id, date, repeat_cycle, row_number() over(partition by id order by repeat_cycle desc) as rnk from table_name)
qry where rnk = 1;
2guxujil

2guxujil3#

你可以用 max() 以及 group by .

select
    t.id,
    max(t.repeat_cycle)
from
    table t
group by
    t.id

其中table是您的真实表名。

yuvru6vn

yuvru6vn4#

我建议您不要使用“date”之类的关键字或“table”之类的表来调用列

select t1.id, t1.date_c, t1.repeat_cycle      
from table_t t1
where (t1.id, t1.repeat_cycle) in (select t2.id, max(t2.repeat_cycle)
                                   from table_t t2
                                   group by t2.id);

这是一个演示

相关问题