10.2 Partitioning

Like aggregate functions, that may operate alone or in relation to a group, window functions may also operate on a group, which is called a partition.

Syntax

  1. <window function>(...) OVER (PARTITION BY <expr> [, <expr> ...])

Aggregation over a group could produce more than one row, so the result set generated by a partition is joined with the main query using the same expression list as the partition.

Continuing the EMPLOYEE example, instead of getting the portion of each employee’s salary over the all-employees total, we would like to get the portion based on just the employees in the same department:

  1. select
  2. id,
  3. department,
  4. salary,
  5. salary / sum(salary) OVER (PARTITION BY department) portion
  6. from employee
  7. order by id;

Results

  1. id department salary portion
  2. -- ---------- ------ ----------
  3. 1 R & D 10.00 0.3448
  4. 2 SALES 12.00 0.6000
  5. 3 SALES 8.00 0.4000
  6. 4 R & D 9.00 0.3103
  7. 5 R & D 10.00 0.3448