【问题标题】:Selecting rows with max value, in correlation to two other columns选择具有最大值的行,与其他两列相关
【发布时间】:2022-11-23 18:32:39
【问题描述】:

我有一个包含三列的表格:区域、国家/地区、计数。 我想将我的表格减少为区域、国家和计数行 - 其中计数在该区域中最大。

例如,如果我有下表:

region | country | count
asia   | jo      | 12
asia   | ir      | 12
asia   | il      | 10  
europe | fr      |  8
europe | it      |  2

我希望得到回报:

region | country | count
asia   | jo      | 12
asia   | ir      | 12
europe | fr      |  8

【问题讨论】:

    标签: postgresql greatest-n-per-group groupwise-maximum


    【解决方案1】:

    您可以通过这种方式实现:首先您需要按region 字段对数据进行分组并获取最大值。然后使用字段regioncount执行一个简单的IN条件

    select * from my_table WHERE (region, count) in (select region, MAX(count) from my_table  GROUP BY region)
    

    演示在sqldaddy.io

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多