PostgreSQL获得具有另一个最大值的不同值

时间:2018-08-09 08:10:23

标签: postgresql max distinct

我有一个具有以下值的表:

id - idProduction - historical - idVehicle - km
1  -      200     -      1     -     258   - 100
2  -      200     -      2     -     258   - 100
3  -      200     -      2     -     259   - 150
4  -      200     -      3     -     258   - 120
5  -      200     -      3     -     259   - 170
6  -      300     -      1     -     100   - 80
7  -      100     -      1     -     258   - 140
8  -      300     -      2     -     325   - 50

对于所有不同的idProduction,我需要获取具有最大历史记录的值。在这种情况下:

4  -      200     -      3     -     258   - 120
5  -      200     -      3     -     259   - 170
7  -      100     -      1     -     258   - 140
8  -      300     -      2     -     325   - 50

这是我第一次使用postgresql,所以我不必怎么做,有人可以帮助我吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

我认为我可以解决我的问题,但是我不确定...:

SELECT id, productions_vehicles.id_production, nu_task_number, id_historical, id_vehicle
FROM productions_vehicles
INNER JOIN
    (SELECT id_production, MAX(id_historical) AS idHistorico
    FROM productions_vehicles
    GROUP BY id_production) topHistorico 
ON productions_vehicles.id_production = topHistorico.id_production 
AND productions_vehicles.id_historical = topHistorico.idHistorico;

答案 1 :(得分:1)

您实际上需要两个请求,您的解决方案看起来不错,还可以使用WITH子句来执行第一个请求:

WITH topHistorico (
    SELECT id_production, MAX(id_historical) SA idHistorico
    FROM productions_vehicles
    GROUP BY id_production)
SELECT id, pv.id_production, nu_task_number, id_historical, id_vehicle
FROM production_vehicles pv
INNER JOIN topHistorico th ON pv.id_production = th.id_production AND pv.id_historical = th.idHistorico

PostgreSQL: Documentation: 9.1: WITH Queries (Common Table Expressions)