我有一张这样的桌子:
+----+---------+----------+ | 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 | +----+-------------------+
汇总行显式重复。
有没有一种方法可以在不使用多个(嵌套)查询的情况下获得此结果?
IT将取决于您的SQL Server,在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`;