Deviation From Partition Average
Compare each row to its partition average with AVG OVER (PARTITION BY): window aggregates keep every row and expose per-group deviation directly.
Code
-- 窗口聚合不改行数:每个员工旁边给出部门均值,相减即得偏差
WITH payroll AS (
SELECT * FROM (VALUES
('alice', 'eng', 120),
('brin', 'eng', 90),
('cyd', 'eng', 90),
('dee', 'sales', 70),
('eli', 'sales', 50)
) AS t(name, dept, kusd)
)
SELECT
name,
dept,
kusd,
AVG(kusd) OVER (PARTITION BY dept) AS dept_avg,
kusd - AVG(kusd) OVER (PARTITION BY dept) AS deviation
FROM payroll
ORDER BY dept, kusd DESC, name;Inside the snippet
At its core this is a single SELECT statement against payroll.
What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; AVG 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-levelWHEREwill not work — use an outer query or a CTE.
Putting it to use
Run it in the payroll 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
- Name the tables involved in this file.
- The references are `payroll`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.