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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which objects does the SQL touch?
- `orders` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.