Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a SUM operation without grouping the results in SQL?

I have a table like this one:

+----+---------+----------+
| 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 | 
+----+---------+----------+

If I perform the following query:

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

I, obviously, get:

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

But I need a table like this one:

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

Where summed rows are explicitly repeated.

Is there a way to obtain this result without using multiple (nested) queries?

like image 217
Luca Avatar asked Mar 04 '10 16:03

Luca


People also ask

Can you SUM without GROUP BY in SQL?

Did you know that you can use the SQL Server aggregate functions SUM, COUNT, MAX, MIN and AVG with an OVER Clause now? Using an OVER clause you can produce individual record values along with aggregate values to different levels, without using a GROUP BY clause.

Does SUM require GROUP BY?

SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group. It is better to identify each summary row by including the GROUP BY clause in the query resulst.

Can you use aggregate functions without GROUP BY?

While all aggregate functions could be used without the GROUP BY clause, the whole point is to use the GROUP BY clause. That clause serves as the place where you'll define the condition on how to create a group. When the group is created, you'll calculate aggregated values.


1 Answers

IT would depend on your SQL server, in Postgres/Oracle I'd use Window Functions. In MySQL... not possible afaik.

Perhaps you can fake it like this:

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`;
like image 181
Wolph Avatar answered Sep 18 '22 14:09

Wolph