Postgresql如何GROUP BY多列并获取所有其他列?

时间:2015-03-31 20:54:43

标签: postgresql group-by

我想按三列分组并从所有列中获取数据。

这很有用,但我没有从lap.valid,lap。“timestamp”和lap.maxspeed_kmh获取数据:

SELECT 
    players.name,
    cars.car,
    tracks.track,
    min(lap.laptime) AS best_laptime
FROM lap
    JOIN playerinsession ON lap.playerinsessionid = playerinsession.playerinsessionid
    JOIN session ON playerinsession.sessionid = session.sessionid
    JOIN tracks ON session.trackid = tracks.trackid
    JOIN cars ON playerinsession.carid = cars.carid
    JOIN players ON playerinsession.playerid = players.playerid
GROUP BY
    players.name,
    cars.car,
    tracks.track;

这就是我想要做的事情:

SELECT 
    players.name,
    cars.car,
    tracks.track,
    min(lap.laptime) AS best_laptime,
    lap.valid,
    lap."timestamp",
    lap.maxspeed_kmh
FROM lap
    JOIN playerinsession ON lap.playerinsessionid = playerinsession.playerinsessionid
    JOIN session ON playerinsession.sessionid = session.sessionid
    JOIN tracks ON session.trackid = tracks.trackid
    JOIN cars ON playerinsession.carid = cars.carid
    JOIN players ON playerinsession.playerid = players.playerid
GROUP BY
    players.name,
    cars.car,
    tracks.track;

但是我得到一个错误“列lap.valid必须出现在GROUP BY ...”,我怎么能解决这个问题呢?

重要的是为每辆车获得最快的单圈时间并跟踪组合。不同车型中的多个玩家每个赛道都有数百个单圈时间。

1 个答案:

答案 0 :(得分:1)

检查distinct on

select distinct on (p.name, c.car, t.track)
    p.name,
    c.car,
    t.track,
    l.laptime as best_laptime,
    l.valid,
    l."timestamp",
    l.maxspeed_kmh
from
    lap l
    join
    playerinsession on l.playerinsessionid = playerinsession.playerinsessionid
    join
    session on playerinsession.sessionid = session.sessionid
    join
    tracks t on session.trackid = t.trackid
    join
    cars c on playerinsession.carid = c.carid
    join
    players p on playerinsession.playerid = p.playerid
order by p.name, c.car, t.track, l.laptime