Efficient query to get last row group by multiple columns
3
votes
2
answers
5917
views
I have a table like the following:
~~~pgsql
CREATE TABLE spreads (
spread_id serial NOT NULL,
game_id integer NOT NULL,
sportsbook_id integer NOT NULL,
spread_type integer NOT NULL,
spread_duration integer NOT NULL,
home_line double precision,
home_odds integer,
away_line double precision,
away_odds integer,
update_time timestamp without time zone NOT NULL,
game_update_count integer NOT NULL
);
~~~
I'm trying to get the last row inserted (max
game_update_count
), for each group of (sportsbook_id, spread_type, spread_duration, game_id)
.
The following query gets me close, but I am not able to select the lines/odds without Postgres complaining.
~~~pgsql
SELECT
spreads.game_id, sportsbook_id, spread_type, spread_duration,
MAX(game_update_count) AS game_update_count
FROM spreads
LEFT JOIN schedule ON schedule.game_id = spreads.game_id
WHERE date >= '2012-01-01' AND date <= '2012-01-02'
GROUP BY
spreads.game_id, sportsbook_id, spread_type, spread_duration
ORDER BY
spread_duration, spread_type, sportsbook_id, spreads.game_id,
game_update_count DESC;
~~~
Anyone have any thoughts on a better approach?
Asked by Jeremy
(33 rep)
Jan 21, 2015, 07:27 AM
Last activity: Feb 24, 2025, 10:38 PM
Last activity: Feb 24, 2025, 10:38 PM