Karthikeyan sundaramoorthi Karthikeyan sundaramoorthi - 4 months ago 18
PHP Question

Get all rows and apply sum on a column

I have a table with four columns and 5 rows, I want all the 5 rows with sum of one column. Is it possible in MySQL?

name id rank points
sam 1 4 34
ram 2 6 45
hari 3 1 87
kum 4 7 56
raj 5 5 20


What I need is name id rank points and sum of points where rank above 4.

Expected result

name id rank points sum
ram 2 6 45 121
kum 4 7 56
raj 5 5 20

Answer

Hmmm . . .

select name, id, rank, points,
       (select sum(t2.points) from t t2 where t2.rank > 4) as `sum`
from t
where rank > 4;

This puts the sum on each row, but that seems like a reasonable approach.