I am trying to get sum of capacity column of last 4 rows of a table in MySQL.
My Table is :
My SQL is :
SELECT tid, sum(capacity) FROM captable ORDER BY tid DESC LIMIT 4
Result is giving different sum. It should be 150+200+250+300 = 900.
I am looking for sum of the red circled numbers.
Advertisement
Answer
You could order using subquery and apply SUM
in the outer query. This query take in consideration that tid is auto_inrement:
SELECT sum(t1.capacity) FROM ( SELECT tid,capacity FROM captable ORDER BY tid DESC LIMIT 4 ) as t1 ;
Result:
last_4_rows_sum 900