SQL window function with a where clause?

前端 未结 2 1895
别跟我提以往
别跟我提以往 2021-02-12 17:50

I\'m trying to correlate two types of events for users. I want to see all event \"B\"s along with the most recent event \"A\" for that user prior to the \"A\" event. How would

2条回答
  •  -上瘾入骨i
    2021-02-12 18:14

    Just tried Gordon's approach using PostgreSQL 9.5.4, and it complained that

    FILTER is not implemented for non-aggregate window functions

    which means using lag() with FILTER is not allowed. So I modified Gordon's query using max(), a different window frame, and CTE:

    WITH subq AS (
      SELECT
        "user", event, time as event_b_time,
        max(time) FILTER (WHERE event = 'A') OVER (
          PARTITION BY "user"
          ORDER BY time
          ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
        ) AS last_event_a_time
      FROM events
      ORDER BY time
    )
    SELECT
      "user", event_b_time, last_event_a_time
    FROM subq
    WHERE event = 'B';
    

    Verified that this works with PostgreSQL 9.5.4.

    Thanks to Gordon for the FILTER trick!

提交回复
热议问题