The SQL standard knows a lesser known feature called GROUPING SETS. One particular side-effect of that feature is that we can group by "nothing" in SQL. E.g. when querying the Sakila database: SELECT count(*) FROM film GROUP BY () This will yield: count | ------| 1000 | What's the point, you're asking? Can't we just … Continue reading How to Group By “Nothing” in SQL
This answer to a beautiful Stack Overflow question I've given recently needs further explanation in a blog post. When working with Microsoft Excel, we can create beautiful and also very insightful Pivot Tables with grand totals. What are they? This is best explained visually. Assuming you have this normalised form for your raw data. As … Continue reading Creating a Microsoft Excel Style Pivot Table With Grand Totals in SQL
At a customer site, I've recently encountered a report where a programmer needed to count quite a bit of stuff from a single table. The counts all differed in the way they used specific predicates. The report looked roughly like this (as always, I'm using the Sakila database for illustration): -- Total number of films … Continue reading How to Calculate Multiple Aggregate Functions in a Single Query
In the recent past, we've explained the syntactic implications of the SQL GROUP BY clause. If you haven't already, you should read our article "Do You Really Understand SQL’s GROUP BY and HAVING clauses?". In essence, adding a GROUP BY clause to your query transforms your query on very implicit levels. The following reminder summarises … Continue reading How SQL GROUP BY Should Have Been Designed – Like Neo4j’s Implicit GROUP BY
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(), … Continue reading Do You Really Understand SQL’s GROUP BY and HAVING clauses?
Every now and then, you come across a requirement that will bring you to your SQL limits. Many of us probably give up early and calculate stuff in Java / [or your language]. Instead, it might've been so easy and fast to do with SQL. If you're working with an advanced database, such as DB2, … Continue reading GROUP BY ROLLUP / CUBE