简体   繁体   English

获取所有行并在列上应用总和

[英]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. 我有一个包含四列和五行的表,我希望所有5行都有一列的总和。 Is it possible in MySQL? 在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. 我需要的是名称id等级点和等于 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. 这将sum放在每一行上,但这似乎是一种合理的方法。

For you and others, the DML & DDL I used is: 对于您和其他人,我使用的DML和DDL是:

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 小提琴: http ://www.sqlfiddle.com/#!9 / dd6260 / 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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