Quantcast
Channel: Question and Answer » postgresql
Viewing all articles
Browse latest Browse all 1138

Postgres – Combine similar queries with extra where clause

$
0
0

I am trying to combine a number of fairly time consuming queries into one (if possible)

The database contains race-track data that records the times for laps completed by drivers (or users here), the database contains the following tables, simplified for brevity:

user_sessions:

user_id (fk)

session_id (fk)

sessions:

session_id (pk)

session_date

track_size

laps:

lap_id (pk)

car_type

lap_number

rest_time

I have some queries that leverage Postgres window functions to find the highest number of consecutive laps for a user in the same type of car, each query returns the session_id from the highest record and total distance covered for those consecutive laps

Both queries are exactly the same however one includes an additional where clause on the inner select (to exclude laps with rests).

My question is, can I combine this into a single query to improve performance? whereby the combined query returns two results (one including rest laps, and one that doesn’t)?

SELECT x.sess_id, round(count(x.*) * x.size,2) 
    FROM ( 
        SELECT l.session_id as sess_id, l.car_type, s.track_size as size,row_number()
        OVER (ORDER BY l.session_id, l.stroke_type, l.lap_number) - l.lap_number AS grp 
        FROM laps as l, user_sessions as us, sessions as s 
        WHERE l.session_id = us.session_id 
        AND us.user_id = :userId 
        AND l.session_id = s.session_id 
        AND CAST(l.car_type as text) = CAST(:car_type as text) 
    ) x ";
    GROUP  BY x.sess_id, x.car_type, grp, x.size 
    ORDER  BY count(x.*) DESC LIMIT  1

Second query

SELECT x.sess_id, round(count(x.*) * x.size,2) 
        FROM ( 
            SELECT l.session_id as sess_id, l.car_type, s.track_size as size,row_number()
            OVER (ORDER BY l.session_id, l.stroke_type, l.lap_number) - l.lap_number AS grp 
            FROM laps as l, user_sessions as us, sessions as s 
            WHERE l.session_id = us.session_id 
            AND us.user_id = :userId 
            AND l.session_id = s.session_id 
            AND CAST(l.car_type as text) = CAST(:car_type as text) 
            AND l.rest_time <= 0
        ) x ";
        GROUP  BY x.sess_id, x.car_type, grp, x.size 
        ORDER  BY count(x.*) DESC LIMIT  1

(I am using PostgreSQL 9.0)


Viewing all articles
Browse latest Browse all 1138

Trending Articles