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.

SqlData Integrity

Code

snippet
-- 窗口聚合不改行数:每个员工旁边给出部门均值,相减即得偏差
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-level WHERE will 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

FAQ

Name the tables involved in this file.
The references are `payroll`.