For a while now, I really have wanted to learn the Windowing Functions in great detail. I know them well enough to make it through a lot of needs, but there are a lot of intricacies that are hard to remember. As I noted in my very first Blogging for Programmers post, writing for your own future needs is some of the best and easiest writing you will do.
When I wrote my “SQL Techniques you should know” presentation, the topic that took the longest was Window Functions. Because of their similarity to GROUP BY, I figured this was the best place to start.
In the title I say “conceptualizing” because this is a big part of how I do a lot of my learning. Take an algorithm or concept and turning it a real feeling pattern I can imagine as I am building the solution to a problem. One of my first presentations (that I have lost the slides for!) was showing how join algorithms work. However, most of the time, that drawing is usually in my head, not something that I draw (sometimes it is actually in a pretty marginal PowerPoint drawing because I can only barely draw).
In this first entry, I wanted to go over the concept of GROUP BY, subtotals, and filtering. It will be a pretty light overview, but the biggest point is to set up a deeper set of examples with window functions, which work like GROUP BY, but it gets a lot more interesting in what you can do.
The code for this article uses a very small table of values because I like to cover the concepts with small sets of data. I would suggest not stopping there and creating a large set of data or use AdventureWorks to try these things out on. Small sets mean easy to replicate answers, but not performance or real feeling answers. If you take the concepts and start to apply them on a sample set or even your real corporate data, you can reinforce the patterns and see how they perform for yourself. But the fake data set means you won’t finish at the “feels like it is right” level of testing, no matter how important it is.
GROUP BY Basics
The purpose of the GROUP BY clause is to be able to do aggregations on all or part of columns across rows in a SELECT statement. An aggregation is something like summing or getting the average of the values in a row, or in recent year, concatenating the string values row by row.
For example, you have all the customers in your database, and you have all of their orders, so you want to see how many orders, and how much money they have spent. The process of writing aggregations with GROUP BY (and to a lesser extent, the window functions) is getting your data into a single, flat set of rows that have the details you want to see activity aggregated by repeated per row along with the values you want to aggregate.
Note: This formation of rows leads people to think that storing a flat set of rows is the best way to create a reporting database. It sort of is, and if you look for details about the star schema pattern, this is what a fact table is built for. Keeping the actual data that you are grouping and aggregating very thin is important. I will use pretty simple datasets for my examples just for simplicity to show the mechanics of the tools.
There are many aggregation functions that I will highlight, but the two core ones that are used most of the time are SUM and COUNT. SUM takes numeric values and adds them up row by row, and COUNT(*) will count the number of rows, while COUNT(value) returns the number of non-null values in a set.
Example
Consider you have the following set of data. Your requirements are to get the total value and count of the sales of the customer. I am only working with id values for the examples, but usually you might then join this to a sale and customer table to get the customer details and probably interesting date values.
SaleId CustomerId Value ------------- ------------ ------1 1 102 1 203 2 304 2 405 2 50 6 2 607 3 708 3 809 4 90
The query you would use to replicate this result is:
SELECT CustomerId, SUM(Value), COUNT(*)FROM SaleGROUP BY CustomerId;
And this is the output you are going for (the code is in the Appendix for the examples that use this table.):
GroupingId SetId Value ------------- ---------- ------1 2 202 6 603 8 804 9 90
It is pretty simple code, and is something you definitely do when you are starting out in SQL, but in the next section I will take a look at how I tend to think about the way group by works.
How this is done conceptually
The first thing you need to understand is that the column (or columns) in the GROUP BY clause is used to split the data formed in the FROM clause into 2 virtual sets. Much like you would normalize this data if you were designing it, the grouped columns form one table, and the other rows form another set that is directly related to the grouped columns.
So consider you are writing the previous query, just FROM and GROUP BY for now.
FROM SaleGROUP BY CustomerId;
This gives us logically these two tables , the Customer, and then the activity you want to aggregate (The CustomerId from the group is logically in both sets because you can in fact use it in aggregations too):
CustomerId CustomerId SaleId Value ---------- ---------- -------------- -----1 1 1 10 1 2 20 2 2 3 30 2 4 40 2 5 50 2 6 60 3 3 7 70 3 8 80 4 4 9 90
Even though this is a simplistic dataset and GROUP BY is fairly simple to understand on its own, what made this illustrations so helpful to me was how well they helped me understand the window functions that we will cover in later posts. Logically they will separate data into two sets in a similar way, but far far more flexibly.
You can only return columns from the table segment formed by the GROUP BY, no matter how many rows exist in the Sale segment. So consider we have the entire query:
SELECT CustomerId, SUM(Value), COUNT(*)FROM SaleGROUP BY CustomerId;
and these first two sets from the table above:
CustomerId CustomerId SaleId Value ---------- ---------- -------------- -----1 1 1 10 1 2 20 2 2 3 30 2 4 40 2 5 50 2 6 60
We can return CustomerId as is, but we can only aggregate values in the SaleId or Value columns.
Note that without a
GROUP BYclause, all rows are treated as one segment with no column that you can simply output.
So SUM(Value) for CustomerId(1) = 10 + 20, and for CustomerId(2) = 30 + 40 + 50 + 60. COUNT(*) just gives you the cardinality of the set so COUNT(*) for CustomerId(1) = 2, and for CustomerId(2) = 4.
As mentioned CustomerId is repeated in the group because you can return. It is guaranteed to be unique (and NULL values are treated as equal in aggregation) but you can also aggregate on the group by columns too (even if in the following query it is semantically nonsensical):
SELECT CustomerId, SUM(CustomerId) as SUMCustomerForSomeReasonFROM SaleGROUP BY CustomerId;
This returns:
| CustomerId | SUMCustomerForSomeReason |
|---|---|
| 1 | 2 |
| 2 | 8 |
| 3 | 6 |
| 4 | 4 |
Example Aggregates
In this next query, I will include the aggregates you get in SQL Server that work with GROUP BY. This is mostly as a bit of documentation as to where to go next and what to do with this.
Note, aggregates is one place where
NULLreally behaves differently from all other calculations.COUNT(*)will return 2 no matter if all columns areNULLin the non-grouped by segment of rows. One of the really confusing outcomes is the when youSUMvalues that include aNULL, the output isn’tNULL. Only in cases where all values are NULL will an aggregate function return a NULL. (Thanks to Steve Jones’ blog “The Sum of Nothing” which was inspired by Pinal Dave’s post “Eleven SQL Server Interview Questions That Look Far Too Easy”. I love that we still have some great bloggers out there.
I added one such example in the following statement that shows off all the aggregate functions that work with a GROUP BY clause.
SELECT CustomerId, SUM(Value) as SUM, AVG(Value) as Average, COUNT(*) as CountRows, COUNT(DISTINCT SaleId) as CountDistinctValues, APPROX_COUNT_DISTINCT(value) as ApproxCountDistinct, COUNT_BIG(*) as CountButReturnsABigInt, COUNT(CASE WHEN VALUE <= 20 THEN Value else NULL END) as CountNoNullValues, MAX(Value) as LargestValueInSet, MIN(Value) as SmallesValueInSet, CHECKSUM_AGG(Value) AS CheckSumRowValues, PRODUCT(Value) as ProductOfEveryValue, STDEV(Value) AS StandardDeviation, STDEVP(Value) AS PopulationStandardDeviation, VAR(Value) AS Variance, VARP(Value) AS PopulationVariance, STRING_AGG(Value,',') WITHIN GROUP (Order by Value DESC) AS CommaListFROM SaleGROUP BY CustomerId;
The output, formatted as a table (I didn’t alter the query for this format, I copied the grid out put and let Redgate’s SQL Prompt’s AI do it for me with by asking it to “pivot the results and format as markdown”). I will give a brief explanation in a table section after this:
| Metric | Customer 1 | Customer 2 | Customer 3 | Customer 4 |
|---|---|---|---|---|
| SUM | 30 | 180 | 150 | 90 |
| Average | 15 | 45 | 75 | 90 |
| CountRows | 2 | 4 | 2 | 1 |
| CountDistinctValues | 2 | 4 | 2 | 1 |
| ApproxCountDistinct | 2 | 4 | 2 | 1 |
| CountButReturnsABigInt | 2 | 4 | 2 | 1 |
| CountNoNullValues | 2 | 0 | 0 | 0 |
| LargestValueInSet | 20 | 60 | 80 | 90 |
| SmallesValueInSet | 10 | 30 | 70 | 90 |
| CheckSumRowValues | 30 | 56 | 22 | 90 |
| ProductOfEveryValue | 200 | 3600000 | 5600 | 90 |
| StandardDeviation | 7.07106781186548 | 12.9099444873581 | 7.07106781186548 | NULL |
| PopulationStandardDeviation | 5 | 11.1803398874989 | 5 | 0 |
| Variance | 50 | 166.666666666667 | 50 | NULL |
| PopulationVariance | 25 | 125 | 25 | 0 |
| CommaList | 20,10 | 60,50,40,30 | 80,70 | 90 |
In the output
- SUM(Value) as SUM – Adds all values together
- AVG(Value) as Average – Adds all non-null values and divides by the count of non-null values
- COUNT(*) as CountRows – Counts the number of rows
- COUNT(DISTINCT SaleId) as CountDistinctValues – Counting on a specific column gives you the count of non-null values, and DISTINCT (here not a bad thing typically) only counts how many different values are in the set
- APPROX_COUNT_DISTINCT(value) as ApproxCountDistinct – Typically used on very large sets, gives a statistically based guess of the number of unique values in a range
- COUNT_BIG(*) as CountButReturnsABigInt – use when counting a number of values that could be greater that the max integer value
- COUNT(CASE WHEN VALUE <= 100 THEN Value else NULL END) as CountNoNullValues – Simple demo of how counting NULL values works. Note that not only does it ignore NULL values, but you will get a warning: Warning: Null value is eliminated by an aggregate or other SET operation unless you choose to SET ANSI_WARNINGS OFF.
- MAX(Value) as LargestValueInSet – The largest value in the set. Simple for numeric values, can be tricky for string values as it is based on collation.
- MIN(Value) as SmallesValueInSet – Like MAX, but gets the smallest.
- CHECKSUM_AGG(Value) AS CheckSumRowValues – Useful for comparing sets of data, does a checksum of all the numeric values in a column. (A cool use of this is to use the CHECKSUM function to checksum a row, then CHECKSUM_AGG to get a checksum of the CHECKSUM values.
- PRODUCT(Value) as ProductOfEveryValue – Multiplies all the values in a group. This can be a very large number fast. Used, as I understand it, in some financial calculations
- STDEV(Value) AS StandardDeviation – Just including for your future knowledge. I only slightly still understand stuff like this.
- STDEVP(Value) AS PopulationStandardDeviation – Same here
- VAR(Value) AS Variance – And here
- VARP(Value) AS PopulationVariance – finally here.
- STRING_AGG(Value,’,’) WITHIN GROUP (ORDER BY Value DESC) AS CommaList – takes every value and returns it as string with a delimiter. Note that I added an ORDER BY to show you can use that syntax with this aggregate only. Most agregates groups have no order.
One more conceptual view of an aggregate
In my previous conceptual view, I said to think of the grouped columns and the grouping columns as two different segments/rowsets, like this:
CustomerId CustomerId SaleId Value ---------- ---------- -------------- -----1 1 1 10 1 2 20 2 2 3 30 2 4 40 2 5 50 2 6 60 3 3 7 70 3 8 80 4 4 9 90
But for GROUP BY you can also think of the aggregation segment as really completely different sets of data. You can’t access data outside of your segment, much like if they were UNION ALL-ed together:
SELECT SELECT CustomerId, SaleId, ValueFROM SaleWHERE CustomerId = 1UNION ALLSELECT CustomerId, SaleId, ValueFROM SaleWHERE CustomerId = 2UNION ALLSELECT CustomerId, SaleId, ValueFROM SaleWHERE CustomerId = 3UNION ALLSELECT CustomerId, SaleId, ValueFROM SaleWHERE CustomerId = 4;
This is important because anytime you need to do something more interesting like compare the values in one group to the other group, you will need multiple passes, like to put it in a CTE and then join the CTE to itself, something like this:
WITH BaseRows AS (SELECT CustomerId, SUM(Value) as ValueSumFROM SaleGROUP BY CustomerId)SELECT TOP 5 *FROM BaseRows CROSS JOIN BaseRows AS BR2WHERE BaseRows.CustomerId <> BR2.CustomerIdORDER BY BaseRows.ValueSum - BR2.ValueSum DESC;
This returns the top value customer and show their comparison to the biggest differential in ValueSum:
| CustomerId | ValueSum | CustomerId | ValueSum |
|---|---|---|---|
| 2 | 180 | 1 | 30 |
| 3 | 150 | 1 | 30 |
| 2 | 180 | 4 | 90 |
| 3 | 150 | 4 | 90 |
| 4 | 90 | 1 | 30 |
The first times you have to write something like this you will see what some of the complexities are with aggregation using GROUP BY when you need to to complex comparisons.
Filtering
There are a few ways you can filter a statement with a GROUP BY.
First in a where clause. The WHERE clause will remove rows from the FROM set, and these rows will not be in the aggregations. For example here are just rows divisible by 20:
SELECT *FROM SaleWHERE Value % 20 = 0;
This returns:
| SaleId | CustomerId | Value |
|---|---|---|
| 2 | 1 | 20 |
| 4 | 2 | 40 |
| 6 | 2 | 60 |
| 8 | 3 | 80 |
So when you group the rows on CustomerId:
SELECT CustomerId, SUM(Value) as SumValue, COUNT(*) as CountRowsFROM SaleWHERE Value % 20 = 0GROUP BY CustomerId;
You can see the sums based only on the rows that made it past the WHERE filter.
| CustomerId | SumValue | CountRows |
|---|---|---|
| 1 | 20 | 1 |
| 2 | 100 | 2 |
| 3 | 80 | 1 |
Then using a HAVING clause, you can filter groups that don’t meet any of the different aggregates you have in the SELECT clause, or any new ones too. You can also include the grouped columns in the HAVING clause, though generally I wouldn’t, based only on style.
SELECT CustomerId, SUM(Value) as SumValue, COUNT(*) as CountRowsFROM SaleWHERE Value % 20 = 0GROUP BY CustomerIdHAVING SUM(Value) < 100;
You can see the SumValue of 100 from the last result is now gone.
| CustomerId | SumValue | CountRows |
|---|---|---|
| 1 | 20 | 1 |
| 3 | 80 | 1 |
If you try to filter on an aggregate in the WHERE clause:
SELECT CustomerId, SUM(Value) as SumValue, COUNT(*) as CountRowsFROM SaleWHERE Value % 20 = 0 and SUM(Value) < 100GROUP BY CustomerId;
You will get this error:
Msg 147, Level 15, State 1, Line 331An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
Summary
In this cursory overview of how the GROUP BY is used to aggregate rows, we looked at the basic patterns of using GROUP BY and the aggregate functions that are available. In the next post, I will look at subtotals in some detail, before starting with actual window functions.
Appendix
This is the data you will need if you want to work the examples as given. Like mentioned, I would encourage you to take it to the next level and try these techniques on some real data (that you are allow to access, naturally!)
CREATE TABLE sale( SaleId INT, CustomerId INT, Value INT);INSERT INTO sale( SaleId, CustomerId, Value)VALUES(1, 1, 10),(2, 1, 20),(3, 2, 30),(4, 2, 40),(5, 2, 50),(6, 2, 60),(7, 3, 70),(8, 3, 80),(9, 4, 90);



Leave a Reply