Search code examples
mysqlsqlaggregate-functions

Get the Sum of negative differences between each row in MySQL


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...


Solution

  • select sum(if(valuediff<0,-valuediff,0))
    from (
        select value-lag(value) over (order by id) as valuediff
        from mysterytablename
    ) valuediff