I'm having a situation where I need to calculate the difference between two consecutive rows of same column. Here is my table named 'orders' structure.
orderid type productsales
1002 Order 120
1002 Refund -35
1003 Order 199
1003 Refund -50
1004 Order 245
1005 Order 80
Now, what I want to Select only those records where the 'productsales' difference between the same orderids
of order type 'Order' & 'Refund' is greater than 0
select orderid
from orders
group by orderid
having sum(case when `type` = 'Order' then productsales else 0 end) +
sum(case when `type` = 'Refund' then productsales else 0 end) > 0
You need to subtract the values from another. But since you stored the -
in the refund I used +
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.