【问题标题】:SQL - How to select a row having a column with max value (+ group by)SQL - 如何选择具有最大值列的行(+分组依据)
【发布时间】:2015-11-10 15:09:14
【问题描述】:

我正在建立这里引用的问题: SQL - How to select a row having a column with max value

date                 value

18/5/2010, 1 pm        40
18/5/2010, 2 pm        20
18/5/2010, 3 pm        60
18/5/2010, 4 pm        30
18/5/2010, 5 pm        60
18/5/2010, 6 pm        25 

我需要查询具有最大值(值)(即 60)的行。所以,我们在这里 得到两行。从那开始,我需要时间戳最低的行 那天(即 2010 年 5 月 18 日,下午 3 点 -> 60)

我们如何根据 Sujee 提供的答案构建:

select high_val, my_key
from (select high_val, my_key
      from mytable
      where something = 'avalue'
      order by high_val desc)
where rownum <= 1

如果数据有第三列“类别”。

date                 value    category

18/5/2010, 1 pm        40      1
18/5/2010, 2 pm        20      1
18/5/2010, 3 pm        60      1
18/5/2010, 4 pm        30      2
18/5/2010, 5 pm        60      2
18/5/2010, 6 pm        25      2 

仅供参考 - 我正在使用 Oracle,并试图避免嵌套连接(因此使用 rownum 技巧)

目标是获得相同的答案,但按类别分组

【问题讨论】:

  • 请解释category 与该问题有什么关系。您在寻找什么结果集?

标签: sql oracle


【解决方案1】:

听起来您想为每个类别选择具有最高 high_val 的行。如果是这样,您可以使用row_number() 根据其high_val 值对类别中的每一行进行排名,并且只选择排名最高的行,即rn = 1

select * from (
    select row_number() over (partition by category order by high_val desc, date asc) rn, *
    from mytable
    where something = 'avalue'
) t1 where rn = 1

【讨论】:

    【解决方案2】:

    只需向order by 添加一个额外的密钥:

    select high_val, my_key
    from (select high_val, my_key
          from mytable
          where something = 'avalue'
          order by high_val desc, date asc
         )
    where rownum = 1;
    

    如果你想在结果集中category,然后在子查询中选择它。

    【讨论】:

    • 这不是只返回一行吗?我正在阅读它,但我认为由于类别而需要两行
    猜你喜欢
    • 2011-02-20
    • 2020-07-11
    • 2017-10-18
    • 2019-01-06
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多