FILTER Clause On Window Aggregates

Attach FILTER to aggregate window functions so one partition pass produces the running total and the refunded subtotal side by side.

SqlData Integrity

Code

snippet
-- FILTER 贴在聚合函数上,可以与 OVER 组合:同一窗口一趟算出多个条件列
SELECT
    customer_id,
    placed_at,
    total_cents,
    refunded,
    -- 窗口内全部行的累计
    SUM(total_cents) OVER customer_window AS running_total_cents,
    -- 同一窗口里只累计退款行
    SUM(total_cents) FILTER (WHERE refunded)
        OVER customer_window AS refunded_cents,
    COUNT(*) FILTER (WHERE refunded)
        OVER customer_window AS refund_count
FROM orders
WINDOW customer_window AS (
    PARTITION BY customer_id
    ORDER BY placed_at
    RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
ORDER BY customer_id, placed_at;

-- FILTER 只能挂在聚合函数上:row_number() 等纯窗口函数没有这个子句

How the snippet works

What runs is SELECT, with orders as the object involved.

Breaking the statements into their working parts: a WHERE clause that scopes which rows one statement can hit; COUNT, SUM aggregation; an ORDER BY that fixes the output order.

Applying it

Run it in the orders database context.

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`orders` — referenced directly, no join needed.