【问题标题】:How find TOP/MAX value for each id via SQL query in Oracle?如何通过 Oracle 中的 SQL 查询找到每个 id 的 TOP/MAX 值?
【发布时间】:2020-11-19 23:13:13
【问题描述】:

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

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 的最大值(它在 repeat_cycle 中的最大数字)。 我的 SQL 查询是错误的,我不知道为什么。有人会建议如何修复它或其他查询。

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

【问题讨论】:

  • 也指定预期结果。

标签: sql oracle max greatest-n-per-group window-functions


【解决方案1】:

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

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);

Here is a demo

【讨论】:

    【解决方案2】:

    你可以使用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;
    

    【讨论】:

      【解决方案3】:

      您可以使用max()group by

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

      table 是你的真实表名。

      【讨论】:

        【解决方案4】:

        您可以使用分析函数:

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-27
          • 2021-05-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多