简体   繁体   中英

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

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.

For you and others, the DML & DDL I used is:

CREATE TABLE `users` (
  `name` varchar(5),
  `id` int,
  `rank` int,
  `points` int
);

INSERT INTO users (
  `name`, `id`, `rank`, `points`
) VALUES (
  'sam', 1, 4, 34
), (
  'ram', 2, 6, 45
), (
  'hari', 3, 1, 87
), (
  'kum', 4, 7, 56
), (
  'raj', 5, 5, 20
);

For doing it, you need to have a separate query:

SELECT SUM(`points`) FROM `users` WHERE `rank` > 4

And I would suggest you to append this at the end.

SELECT *, (
  SELECT SUM(`points`) FROM `users` WHERE `rank` > 4
) AS `sum` FROM `users` WHERE `rank` > 4

The above will give this as output:

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

Fiddle: http://www.sqlfiddle.com/#!9/1dd6260/5

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM