【问题标题】:Postgres Query: Select the row with maximum value on a column from two distinct rowsPostgres查询:从两个不同的行中选择列上具有最大值的行
【发布时间】:2021-11-10 22:31:09
【问题描述】:
 user_id | sum  | app_id | app_count
---------+------+--------+-----------
       1 |  100 |      3 |         1
       2 |  300 |      2 |         1
       4 | 1100 |      1 |         2
       4 | 1100 |      4 |         1

如何编写查询,以便根据 app_count 的等级选择不同的 user_id

这是我想要的结果:

     user_id | sum  | app_id | app_count
    ---------+------+--------+-----------
           1 |  100 |      3 |         1
           2 |  300 |      2 |         1
           4 | 1100 |      1 |         2

【问题讨论】:

  • 重要细节:app_count可以是NULL吗?
  • 不,不能为空

标签: sql postgresql window-functions


【解决方案1】:

在 Postgres 中,您将使用 distinct on:

select distinct on (user_id) t.*
from t
order by user_id, app_count desc;

【讨论】:

  • 您好@Gordon,如果两个 app_count 字段 (user_id = 4) 具有相同的值,则希望选择不同的行并为 app_id 列返回 null。我怎样才能做到这一点?
  • @Urchboy 。 . .请使用示例数据提出一个新问题,并明确说明您想要做什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-15
  • 2018-12-16
  • 2013-02-23
  • 2021-07-23
  • 2023-03-09
  • 2021-01-26
  • 2021-08-16
相关资源
最近更新 更多