我有一张像这样的表:
+----+---------+----------+
| 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 |
+----+-------------------+
明确重复求和的行。
有没有办法在不使用多个(嵌套)查询的情况下获得此结果?
答案 0 :(得分:10)
IT将依赖于您的SQL服务器,在Postgres / Oracle中我会使用Window Functions。在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`;
答案 1 :(得分:1)
没有AFAIK。你必须使用像
这样的连接SELECT t.`id`, tsum.sum AS `sum`
FROM `test` as t GROUP BY `group`
JOIN (SELECT `id`, SUM(`value`) AS `sum` FROM `test` GROUP BY `group`) AS tsum
ON tsum.id = t.id