Consecutive Funnel Steps With LAG

Count consecutive funnel conversions with LAG(event, n) over user-ordered events: a step only counts when its predecessor steps happened.

SqlData Fetching

Code

snippet
-- 连续漏斗:cart 的前一条事件必须是 view,checkout 的前两条必须是 view→cart
-- 只看同用户按时间排序后的事件流;乱序或漏步的用户不计入
WITH ordered AS (
    SELECT
        user_id,
        event,
        LAG(event, 1) OVER (PARTITION BY user_id ORDER BY ts, event) AS prev1,
        LAG(event, 2) OVER (PARTITION BY user_id ORDER BY ts, event) AS prev2
    FROM funnel_events
    WHERE event IN ('view', 'cart', 'checkout', 'purchase')
)
SELECT
    COUNT(*) FILTER (WHERE event = 'view') AS viewed,
    COUNT(*) FILTER (WHERE event = 'cart'
                     AND prev1 = 'view') AS view_to_cart,
    COUNT(*) FILTER (WHERE event = 'checkout'
                     AND prev1 = 'cart' AND prev2 = 'view') AS cart_to_checkout,
    COUNT(*) FILTER (WHERE event = 'purchase'
                     AND prev1 = 'checkout' AND prev2 = 'cart') AS checkout_to_purchase
FROM ordered;

Inside the snippet

What runs is SELECT, with funnel_events and ordered as the object involved.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; COUNT aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

Watch out for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Putting it to use

The funnel_events table is the working surface here.

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`funnel_events`, `ordered` — referenced directly, no join needed.