How do I calculate the negative difference between each row and return as a total sum?
For example (col "fictional difference" is only for better understanding):
id | value | fictional difference |
---|---|---|
0 | 63 | 0 -> ignrore |
1 | 61 | -2 |
2 | 55 | -6 |
3 | 62 | +7 -> ignore |
4 | 57 | -5 |
5 | 71 | +14 -> ignore |
The goal would be the absolute sum of all negative differences: 13.
Has anybody an idea how to achieve this?
I’ve tried this https://stackoverflow.com/a/29779698/12350648 but it doesn’t work for my problem…
3
Answers
I’m not saying this is the best solution, but I took the example which didn’t work for you and rebuild it slightly into this:
The inner SELECT builds a table with the difference called
diffTable
and then the outer SELECT sums the negative results.See: http://sqlfiddle.com/#!9/62bc4d/12
I’m using a table join to achieve this.