【问题标题】:Query associated MAX column with all it's fields in Postgres使用 Postgres 中的所有字段查询关联的 MAX 列
【发布时间】:2021-03-27 08:09:06
【问题描述】:

我有三个数据库表:

  • 汽车
    • 身份证
  • 速度
    • 身份证
    • 实际速度
    • car_id
    • gear_id
  • 齿轮
    • 身份证

我想选择所有汽车的最高速度以及它们达到最高速度的档位。我得到了以下查询:

SELECT MAX(speed.actual_speed)
FROM car
INNER JOIN speed ON car.id = speed.car_id
GROUP BY car.id;

此查询有效,但不返回齿轮。如果我在选择SELECT MAX(speed.actual_speed), speed.gear_id 中包含gear_id。数据库抱怨 gear_id 应该包含在 group by 或聚合函数中。

但如果我将它包含在GROUP BY car.id, speed.gear_id 的组中,则查询会返回我不感兴趣的所有齿轮的最大速度。

有没有办法让所有汽车以最高速度和达到最高速度的档位恢复?

【问题讨论】:

  • 我删除了不一致的数据库标签。请仅使用您真正使用的数据库进行标记。

标签: sql postgresql subquery sql-order-by greatest-n-per-group


【解决方案1】:

一个简单且可移植的解决方案使用相关子查询:

select s.*
from speed s
where s.actual_speed = (select max(s1.actual_speed) from speed s1 where s1.car_id = s.car_id)

这将使(car_id, actual_speed) 上的索引受益。

在 Postgres 中,我会推荐 distinct on:

select distinct on (car_id) s.*
from speed s
order by car_id, actual_speed desc

或者,如果您想允许平局:

select *
from (
    select s.*, rank() over(partition by car_id order by actual_speed desc) rn
    from speed s
) s
where rn = 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多