BBampaa

Lessons › SQL › Chapter 6: Window Functions

SQL lesson

SUM() OVER (PARTITION BY) - partition total

A window function works out a group total, like GROUP BY, but keeps every row. Each row gets its group's total in a new column next to it. PARTITION BY says which group. PARTITION BY category means every Electronics order gets the Electronics total, and every Clothing order gets the Clothing total.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

A group total on every row

SELECT *, SUM(revenue) OVER (PARTITION BY category) AS category_total
FROM orders

Result:

order_idcategoryrevenuecategory_total
O2001Electronics299.99598.99
O2002Electronics149.5598.99
O2004Electronics149.5598.99
O2005Clothing210.0299.0
O2003Clothing89.0299.0

Step by step

  1. Adds up revenue, the same as with GROUP BY.
    SELECT *, SUM(revenue) OVER (PARTITION BY category) AS category_total FROM orders
  2. OVER means: don't squash the rows. Put the answer next to each one instead.
    SELECT *, SUM(revenue) OVER (PARTITION BY category) AS category_total FROM orders
  3. Each row gets the total of its own category only.
    SELECT *, SUM(revenue) OVER (PARTITION BY category) AS category_total FROM orders

Practice

Try each one in your head first, then open the answer.

1. Using orders, show every order with its category's total revenue next to it. Name it category_total.
SELECT *, SUM(revenue) OVER (PARTITION BY category) AS category_total FROM orders
2. Using orders, show each category's average revenue next to every order instead. Name it category_avg.
SELECT *, AVG(revenue) OVER (PARTITION BY category) AS category_avg FROM orders
3. Using employees, show every employee with their department's average salary next to it. Name it dept_avg.
SELECT *, AVG(salary) OVER (PARTITION BY department) AS dept_avg FROM employees
4. Using store_sales, show every sale with its channel's total revenue next to it. Name it channel_total.
SELECT *, SUM(revenue) OVER (PARTITION BY channel) AS channel_total FROM store_sales
5. Using shipments, show every shipment with how many shipments its carrier has. Name it carrier_shipments.
SELECT *, COUNT(*) OVER (PARTITION BY carrier) AS carrier_shipments FROM shipments

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed