Reputation: 93
i started to learn the PARTITION BY methode with agregate functions but i dont understand why should i use ORDER BY for in this query . i want to SUM the total amount of sales in $ on "standart paper " in each year this is my code :
SELECT standard_amt_usd,
DATE_TRUNC('year', occurred_at) as year,
SUM(standard_amt_usd) OVER (PARTITION BY DATE_TRUNC('year', occurred_at)
ORDER BY occurred_at) AS running_total
FROM orders ;
the answers i get are correct but i still dont understand why in need to ese ORDER BY in here and what will happen if i wont use it ? thank for the help:)
Upvotes: 0
Views: 99
Reputation: 1270723
Run this query:
SELECT standard_amt_usd,
DATE_TRUNC('year', occurred_at) as year,
SUM(standard_amt_usd) OVER (PARTITION BY DATE_TRUNC('year', occurred_at)
ORDER BY occurred_at
) AS running_total,
SUM(standard_amt_usd) OVER (PARTITION BY DATE_TRUNC('year', occurred_at)
) AS group_total
FROM orders ;
You will probably see the difference right away. The ORDER BY
says to do the summation "up to" this row. Without the ORDER BY
, the summation is the same on all rows with the same PARTITION BY
key.
Upvotes: 2
Reputation: 738
ORDER BY has mainly two rules:
Upvotes: 0