As we saw in the previous chapter, aggregation functions behave in the following way:
![](https://static.packt-cdn.com/products/9781838985288/graphics/assets/4837d21e-fc8e-4a49-9425-bd116909914a.png)
The data is first sorted and then aggregated; the data is then flattened through aggregation. This is what happens when we execute the following statement:
forumdb=# select category,count(*) from posts group by category order by category;
Alternatively, we can decide to use window functions by executing the following statement:
forumdb=# select category, count(*) over (partition by category) from posts order by category;
category | count
----------+-------
10 | 1
11 | 3
11 | 3
11 | 3
12 | 1
(5 rows)
Window functions create aggregates without flattening the data into a single row. However, they replicate it for all the rows to which the grouping functions refer. The behavior of PostgreSQL is depicted in the following diagram:
![](https://static.packt-cdn.com/products/9781838985288/graphics/assets/ca5d6224-cdea-4456-b95b-6e0fd413b615.png)
This is the reason that the distinct keyword has to be added to the preceding query if we want to obtain the...