Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning sum of group of rows with each row

Tags:

sql

mysql

Can the sum of column values for rows meeting selection criteria be returned not only with each individual row but for multiple groups meeting the same criteria?

For example, consider:

id  order_id    quantity
1   1           1
2   1           3
3   1           5
4   2           2
5   2           4

What MySQL SELECT query could return the follow results:

id  order_id    quantity    order_sum
1   1           1           9
2   1           3           9
3   1           5           9
4   2           2           6
5   2           4           6

EDIT: follow-up question: assuming the results are produced from a query with multiple conditions, how would these conditions be handled in the final query?

like image 571
pseudonymo Avatar asked Aug 02 '12 19:08

pseudonymo


People also ask

How do I sum each row in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

Can we use sum with 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 we use sum function without GROUP BY?

If you know the values to always be the same, then one simple (although not necessarily optimized) solution is to wrap your original GROUP BY query in another query (making the original a subquery) and then use the SUM function in the outer query, without a GROUP BY clause.

How can I sum multiple rows with same ID in SQL Server?

To sum rows with same ID, use the GROUP BY HAVING clause.


1 Answers

You can use a subquery in the "from" clause:

select  t.*, tsum.sumquantity
from t join
     (select t.orderid, sum(quantity) as sumquantity
      from t
      group by t.order_id
     ) tsum
     on t.orderid = tsum.orderid

The advantage of putting it in the "from" clause is that you can have multiple variables. For instance, you could add the number of orders, the maximum quantity, the number of times exactly 1 quantity appears, and so on.

like image 82
Gordon Linoff Avatar answered Oct 06 '22 07:10

Gordon Linoff