Group by squashes rows into one per group. But sometimes you want to keep every row, and still see a group number next to it, like each book's price beside its genre's average. That's a window function.
Avg price over partition by genre averages the price within each book's genre, without squashing the rows. Then we subtract to see how far each book is from the average. Run it. Every cooking and tech book, next to its genre average.
query.sqlsql
SELECT title, genre, price, round(avg(price) OVER (PARTITION BY genre), 2) AS genre_avg, price - round(avg(price) OVER (PARTITION BY genre), 2) AS diffFROM booksWHERE genre IN ('Cooking', 'Technology')ORDER BY genre, price DESC;
Output
title | genre | price | genre_avg | diff
--------------------------+------------+-------+-----------+-------
Spice Roads | Cooking | 27.99 | 24.82 | 3.17
The Quiet Kitchen | Cooking | 24.99 | 24.82 | 0.17
One Pan Dinners | Cooking | 21.49 | 24.82 | -3.33
Python for Curious Minds | Technology | 34.99 | 32.32 | 2.67
Data for Everyone | Technology | 31.99 | 32.32 | -0.33
SQL in a Weekend | Technology | 29.99 | 32.32 | -2.33
(6 rows)
Over turns an aggregate into a window function. Partition by splits rows into groups. Order by inside over sets an order, for running totals and ranks. And an empty over uses every row.