Skip to content
Advertisement

Using Over Partition in sql compared with group by

Given the table creation code bellow, is there an alternative method(s) to display the same result to

using group by and count(*)? And what’s the difference in this case?

Advertisement

Answer

This query puts the total for each colour on each row:

Before window functions, a typical solution would be a correlated subquery:

You can also express this using join and aggregation:

These are not 100% the same. The difference is that the original code will return the count of colour even when the value is NULL. This code returns 0.

So, a more precise equivalent would be:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement