Partitioned Running Totals
Question:
The cats must be ordered first by breed and second by name. They are about to enter an elevator one by one. When all the cats of the same breed have entered they leave. We would like to know what the running total weight of the cats is.
Return: name, breed, running total weight
Order by: breed, name
Show Table
Cats:
| name | varchar |
| breed | varchar |
| weight | float |
| color | varchar |
| age | int |
Show Desired Output
Desired output:
| name | breed | running_total_weight |
| Charlie | British Shorthair | 4.80 |
| Smudge | British Shorthair | 9.70 |
| Tigger | British Shorthair | 13.50 |
| Millie | Maine Coon | 5.40 |
| Misty | Maine Coon | 11.10 |
| Puss | Maine Coon | 16.20 |
| Smokey | Maine Coon | 22.30 |
| Ashes | Persian | 4.50 |
| Felix | Persian | 9.50 |
| Molly | Persian | 13.70 |
| Alfie | Siamese | 5.50 |
| Oscar | Siamese | 11.60 |
Query Window:
Correct output but can you use 'partition by'?
×
Good work!
Over coupled with partition by allows us to further break down our aggregate functions,
it is often used for running totals of types or classes of items.
next question
Show Answer
Answer:
select name, breed,
sum(weight) over (partition by breed order by name) as running_total_weight
from cats