I’m trying to sum a column based on a condition in another column with partition by in SQL, but it’s not working. So I hope somebody can help me with this.
My table is like this:
Group_1 | Group_2 | Date | Value |
---|---|---|---|
A | D | 01/01/2021 | 1 |
A | D | 01/02/2021 | 3 |
A | E | 01/03/2021 | 5 |
B | D | 01/01/2021 | 7 |
B | D | 01/02/2021 | 9 |
B | E | 01/03/2021 | 11 |
B | D | 01/05/2021 | 17 |
B | D | 01/03/2021 | 13 |
B | E | 01/04/2021 | 13 |
C | D | 01/01/2021 | 7 |
C | D | 01/02/2021 | 10 |
So, I need to sum the values of [Value] for all rows where there is a ‘D’ on [Group_2] that is older than the first ‘E’ on the same group (if it exists) for each group of [Group_1].
And the result should be like:
Group_1 | Group_2 | Sum |
---|---|---|
A | D | 4 |
B | D | 16 |
C | D | 17 |
Anybody knows how can I solve this kind of problem?
2
Answers
Try the following aggregation with
NOT EXISTS
:See a demo.
Fiddle