0

I have a similar requirement as this question and I'd want to improve on 1a section of the answer

I was able to extract the most recent row per user using the solution. However, my table has an enum column log_type with the values SYSTEM LOG, APPLICATION LOG, and DATABASE LOG, and I'd like to get the three most recent log types for each user.

user_1      SYSTEM_LOG             2021-02-01 00:00:00.000+01
user_1      APPLICATION_LOG        2021-02-01 01:00:00.000+01
user_1      DATABASE_LOG           2021-02-01 00:30:00.000+01
...

I guess below query is only fetching one row in the recursive query

WITH RECURSIVE cte AS (
   (                                -- parentheses required
   SELECT user_id, log_type, log_date, payload
   FROM   log
   WHERE  log_date <= :mydate
   ORDER  BY user_id, log_type, log_date DESC NULLS LAST
   LIMIT  1
   )
   UNION ALL
   SELECT l.*
   FROM   cte c
   CROSS  JOIN LATERAL (
      SELECT l.user_id, l.log_type, l.log_date, l.payload
      FROM   log l
      WHERE  l.user_id > c.user_id  -- lateral reference
      AND l.log_type > c.log_type -------------------- this is what i need
      AND    log_date <= :mydate    -- repeat condition
      ORDER  BY l.user_id, l.log_type, l.log_date DESC NULLS LAST
      LIMIT  1
      ) l
   )
TABLE  cte
ORDER  BY user_id, log_type;

Any help would be really appreciated. Thanks

sumanth
  • 689
  • 2
  • 15
  • 32

0 Answers0