如何应用SUM操作而不在SQL中分组结果?

前端之家收集整理的这篇文章主要介绍了如何应用SUM操作而不在SQL中分组结果?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一张这样的桌子:
+----+---------+----------+
| id | group   | value    |
+----+---------+----------+
|  1 | GROUP A | 0.641028 | 
|  2 | GROUP B | 0.946927 | 
|  3 | GROUP A | 0.811552 | 
|  4 | GROUP C | 0.216978 | 
|  5 | GROUP A | 0.650232 | 
+----+---------+----------+

如果我执行以下查询

SELECT `id`,SUM(`value`) AS `sum` FROM `test` GROUP BY `group`;

我显然得到:

+----+-------------------+
| id | sum               |
+----+-------------------+
|  1 |  2.10281205177307 | 
|  2 | 0.946927309036255 | 
|  4 | 0.216977506875992 | 
+----+-------------------+

但我需要像这样的桌子:

+----+-------------------+
| id | sum               |
+----+-------------------+
|  1 |  2.10281205177307 | 
|  2 | 0.946927309036255 | 
|  3 |  2.10281205177307 | 
|  4 | 0.216977506875992 | 
|  5 |  2.10281205177307 | 
+----+-------------------+

其中相加行被明确地重复.

有没有办法获得这个结果,而不使用多个(嵌套)查询

解决方法

它将依赖于您的sql Server,在Postgres / Oracle中我将使用Window函数.在MysqL …不可能afaik.

也许你可以这样假装:

SELECT a.id,SUM(b.value) AS `sum`
FROM test AS a
JOIN test AS b ON a.`group` = b.`group`
GROUP BY a.id,b.`group`;

猜你在找的MsSQL相关文章