For a project using Rails 4.2.5 and Postgres 9.3, I am trying to implement some query similar to "Query #3" suggested in PostgreSQL - fetch the row which has the Max value for a column
-- use Window Functions
-- performs a SINGLE scan of the table
SELECT DISTINCT ON (usr_id)
last_value(time_stamp) OVER wnd,
last_value(lives_remaining) OVER wnd,
usr_id,
last_value(trans_id) OVER wnd
FROM lives
WINDOW wnd AS (
PARTITION BY usr_id ORDER BY time_stamp, trans_id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
);
Beside model.find_by_sql
and hacky model.joins
, is it possible to add the WINDOW clause? I find a hack using joins
to specify both WHERE
and WINDOW
clauses, but the readability is out of window (pun intended :). I also like to add a WITH
clause before the SELECT
, and then the joins
hack won't work at all.
Any suggestion is greatly appreciated.