SQL - 如何选择具有最大值列的行(+分组)

4

我在参考以下问题的基础上进行构建: SQL - 如何选择具有最大值列的行


该问题涉及到如何使用SQL语句选择具有最大值列的行。
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 

i need to query for the row having max(value)(i.e. 60). So, here we get two rows. From that, I need the row with the lowest time stamp for that day(i.e 18/5/2010, 3 pm -> 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
如果数据有第三列“category”。
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技巧)

目标是通过分类分组,得到相同的答案


请解释一下“类别”与问题有什么关系。您要寻找什么结果集? - Gordon Linoff
2个回答

4

听起来您想要选择每个类别中具有最高 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

0

只需在 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,那么请在子查询中选择它。

这不会只返回一行吗?我正在阅读它,但是因为类别的原因,我认为我需要两行。 - Stephane Maarek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接