Skip to content
Advertisement

SQL: Select the Running Total of Column C for pairwise combinations of two other columns A and B

I’m trying to query a table and calculate the running sum of a column’s values for pairwise combinations of two other columns.

Specifically, given the following table:

I want to query a column that calculates the cumulative sum for each bucket/label pair.

Put another way, I want to be able to write a query that selects bucket, label, and a third column that’s the cumulative sum of the “amount” column for every entry with a label that matches that row’s label. For example, for the above example, the third column should have the values:

In other words, the value 5 is the sum of 1 and 4 (the first two amounts for the “A” label), the value 7 is the sum of 2 and 5 (the first two amounts of the “B” label), etc.

I know I can get the cumulative sum for the entire column by doing something like:

but I’m not sure how to split it up by label.

Any help is much appreciated!

Advertisement

Answer

You want a partition by clause:

Although ORDER BY amount works for your data, I think you might really want the bucket as well:

Here is a db<>fiddle. Note that this uses MySQL 8, because your create/insert code is compatible with MySQL.

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