There are some things in SQL that we simply take for granted without thinking about them properly.
One of these things are the
GROUP BY and the less popular
HAVING clauses. Let’s look at a simple example. For this example, we’ll reiterate the example database we’ve seen in this previous article about the awesome LEAD(), LAG(), FIRST_VALUE(), LAST_VALUE() functions:
Before there were window functions, aggregations were made only with
GROUP BY. A typical question that we could ask our database using SQL is:
What are the top 3 average government debts in percent of the GDP for those countries whose GDP per capita was over 40’000 dollars in every year in the last four years
REad full article here, Do You Really Understand SQL’s GROUP BY and HAVING clauses?.