Postgres "column must appear in the GROUP BY clause or be used in an aggregate function" 的另一个问题

Postgres another issue with "column must appear in the GROUP BY clause or be used in an aggregate function"

我的 Postgres 数据库中有 2 个 table。

vehicles
- veh_id PK
- veh_number


positions
- position_id PK
- vehicle_id FK
- time
- latitude
- longitude
.... few more fields

我在每个车辆的位置 table 中都有多个条目。我想获得所有车辆位置,但最新的位置(时间字段是最新的)。我试过这样的查询:

SELECT * 
FROM positions
GROUP BY vehicle_id
ORDER BY time DESC

但是出现错误:

column "positions.position_id" must appear in the GROUP BY clause or be used in an aggregate function

我尝试将其更改为:

SELECT * 
FROM positions
GROUP BY vehicle_id, position_id
ORDER BY time DESC

但它不会对条目进行分组。

我试图找到类似的问题,例如:

PostgreSQL - GROUP BY clause or be used in an aggregate function

GroupingError: ERROR: column must appear in the GROUP BY clause or be used in an aggregate function

但我并没有真正帮助解决我的问题。

你能帮我解决我的问题吗?

如果您在 SELECT 上有列,则很简单,这些列也应该在 GROUP 部分,除非它们用聚合函数包装

也不要使用 * 使用列名

  SELECT col1, col2, MAX(col3), COUNT(col4), AVG(col5) -- aggregated columns 
                                                       -- dont go in GROUP BY
  FROM yourTable  
  GROUP BY  col1, col2   -- all not aggregated field

现在关于您的查询,看起来您想要

SELECT *
FROM (
     SELECT * ,
            row_number() over (partition by vehicle_id order by time desc) rn
     FROM positions
     ) t
WHERE t.rn = 1;

尝试使用这个 group by 子句 分组依据 position_id,vehicle_id 主键然后 FK