Aggregating data in SQL

Mar 06, 2023

Intro

I’ve got the following Order table:

OrderIdUserArticle
1a@business.netpen
2a@business.netnotebook
3a@business.netstapler
4b@business.netpen
6b@business.netpen
5b@business.netnotebook

I want to aggregate the data and group it by User it into the following table:

UserArticles
a@business.netpen,notebook,stapler
b@business.netpen,pen,notebook

MySql/MariaDB

Here the magic word GROUP_CONCAT will yeild the desired results.

SELECT [User], GROUP_CONCAT(Article SEPARATOR ',') AS Articles
FROM Order
GROUP BY [User];

Json Aggregation

Sometimes I want to aggregate in JSON, because most good SQL stacks have decent JSON parsing.

MySql/MariaDB has a thing called JSON_ARRAYAGG and works something like this:

SELECT [User], JSON_ARRAYAGG(Article) AS Articles
FROM Order
GROUP BY [User];

And it will produce this:

UserArticles
a@business.net[“pen”,“paper”,“stapler”]
b@business.net[“pen”,“pen”,“stapler”]

Neat!

T-SQL

MS Sql Server and Azure SQL use T-SQL and the magic words are slightly different.

STRING_AGG is the T_SQL equivalent of GROUP_CONCAT

SELECT [User], STRING_AGG(Article, ',') AS Articles
FROM Order
GROUP BY [User];

Json Aggregation

Unfortunately T-SQL still doesn’t provide a JSON alternative so I just do this:

SELECT [User], JSON_QUERY('[' + STRING_AGG('"' + Article + '"', ',') + ']') AS Articles
FROM Order
GROUP BY [User];
sql
Creative

Yasen Dinkov

7 levels of sessionless tokens

Syncing Feature App Configuration Flags