[英]How to get highest value for each group by checking with two columns value
我下面有這個表test_table
USER_ID | YEAR | MONEY
----------------------
1 | 0 | 0
1 | 12 | 12
1 | 48 | 12
2 | 15 | 15
2 | 10 | 20
3 | 0 | 0
所以我想退還錢最高的那一行。 例如,行返回將是這樣的
USER_ID | YEAR | MONEY
----------------------
1 | 12 | 12
1 | 48 | 12
2 | 10 | 20
3 | 0 | 0
但是,由於用戶ID 1具有相同的貨幣價值,因此我想檢查該貨幣金額的最高年份並返回結果。 預期結果應該是
USER_ID | YEAR | MONEY
----------------------
1 | 48 | 12
2 | 10 | 20
3 | 0 | 0
是否有可能得到這樣的行?
這是在線測試您的查詢的鏈接http://sqlfiddle.com/#!9/2e5660/1
您可以嘗試使用相關子查詢
select userid, moneyval,max(year) as year
from
(
select * from t a
where moneyval in
(select max(moneyval) from t b where a.userid=b.userid)
)A group by userid, moneyval
OUTPUT:
userid moneyval year
1 12 48
2 20 10
3 0 0
您可以使用不存在來獲取金額(和年份)為最大值的行:
select t.*
from test_table t
where not exists (
select 1 from test_table
where userid = t.userid and (
money > t.money or (money = t.money and year > t.year)
)
)
參見演示 。
結果:
| userid | money | year |
| ------ | ----- | ---- |
| 1 | 12 | 48 |
| 2 | 20 | 10 |
| 3 | 0 | 0 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.