简体   繁体   English

如何通过检查两列值来获取每个组的最高价值

[英]How to get highest value for each group by checking with two columns value

I have this table test_table below 我下面有这个表test_table

USER_ID | YEAR | MONEY
----------------------
  1     |  0   |  0
  1     | 12   | 12
  1     | 48   | 12
  2     | 15   | 15
  2     | 10   | 20
  3     |  0   |  0

So I am trying to return the row which has the highest money. 所以我想退还钱最高的那一行。 For example, the row return would be like this 例如,行返回将是这样的

USER_ID | YEAR | MONEY
----------------------
  1     | 12   | 12
  1     | 48   | 12
  2     | 10   | 20
  3     |  0   |  0

But because User ID 1 has the same value for money, I would like to check for the highest year of that money amount and return the result. 但是,由于用户ID 1具有相同的货币价值,因此我想检查该货币金额的最高年份并返回结果。 The expected result should be 预期结果应该是

USER_ID | YEAR | MONEY
----------------------
  1     | 48   | 12
  2     | 10   | 20
  3     |  0   |  0

Is it possible to get row like this? 是否有可能得到这样的行?

Here is the link to test your query online http://sqlfiddle.com/#!9/2e5660/1 这是在线测试您的查询的链接http://sqlfiddle.com/#!9/2e5660/1

You can try using correlated subquery 您可以尝试使用相关子查询

DEMO DEMO

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: OUTPUT:

userid  moneyval    year
1        12          48
2        20          10
3        0           0

You can use not exists to get the rows with maximum values in money (and year): 您可以使用不存在来获取金额(和年份)为最大值的行:

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

See the demo . 参见演示
Results: 结果:

| userid | money | year |
| ------ | ----- | ---- |
| 1      | 12    | 48   |
| 2      | 20    | 10   |
| 3      | 0     | 0    |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM