I do understand window functions and group by separately.
But what happens when you use both a window function and a group by clause in the same query ?
group by
?The reason why window functions are not allowed in GROUP BY is the order of operations in SQL. The clauses of a SQL query are processed in a different order than they are written in the query.
Before we start, it is important to note that in terms of the order of operations in SQL, window functions come in sixth on the list. This is important because based off of this logical order, window functions are allowed in SELECT and ORDER BY, but they are not allowed in FROM , WHERE , GROUP BY , or HAVING clauses.
In short and very simplified: window functions retain result row, group by squashes them.
Window functions perform calculations on a set of rows that are related together. But, unlike the aggregate functions, windowing functions do not collapse the result of the rows into a single value. Instead, all the rows maintain their original identity and the calculated result is returned for every row.
Quote from the manual:
If the query contains any window functions, these functions are evaluated after any grouping, aggregation, and HAVING filtering is performed
emphasis mine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With