[英]SQL - How to select a row having a column with max value (+ group by)
我正在構建這里引用的問題: 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
我需要查詢具有max(value)的行(即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
如果數據有第3列“類別”。
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技巧)
目標是獲得相同的答案,但是按類別分組
聽起來你想要為每個類別選擇具有最高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
只需order by
以下方式為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
,請在子查詢中選擇它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.