Search code examples
sqlpostgresqlsql-order-bywindow-functions

what is ORDER BY useful for when i do PARTITION BY


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:)


Solution

  • 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.