Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum multiple rows

Tags:

sql

mysql

So I have a table like this:

id    mod    n1    n2    n3
1     1      1     1
1     2            2
1     3                  3
2     1      1
2     2            2
3     1      1

And I want to sum up each value for all the rows for a specific id into a column call total, but I don't want to group the id together because they have different mod number. I want a result like this:

id    mod   total
1     1     7
1     2     7
1     3     7
2     1     3
2     2     3
3     1     1

I can't use group by because it will give me the total for just each individual rows. How do I achieve the result that I want?

like image 902
user974047 Avatar asked Oct 12 '12 12:10

user974047


People also ask

How do I sum multiple rows in Excel?

If you need to sum a column or row of numbers, let Excel do the math for you. Select a cell next to the numbers you want to sum, click AutoSum on the Home tab, press Enter, and you're done. When you click AutoSum, Excel automatically enters a formula (that uses the SUM function) to sum the numbers.

How do I sum multiple rows into one?

Combine rows in Excel with Merge Cells add-in To merge two or more rows into one, here's what you need to do: Select the range of cells where you want to merge rows. Go to the Ablebits Data tab > Merge group, click the Merge Cells arrow, and then click Merge Rows into One.

How do you sum multiple lines?

The hotkey or shortcut of AutoSum function are Alt + = keys in Excel. Select a list of data in Excel, and then press the Alt + = keys simultaneously, and then it will add the sum value below this list.


2 Answers

You could do something like this:

SELECT `table`.`id`, `mod`, mySum
FROM `table` 
JOIN (SELECT `id`, SUM(n1) + SUM(n2) + SUM(n3) AS mySum
        FROM `table` GROUP BY `id`) as grpTable
ON `table`.`id` = `grpTable`.`id`

Not sure about the performance of this though...

like image 160
rael_kid Avatar answered Sep 29 '22 06:09

rael_kid


Try:

select t.id, t1.mod, t.total
from tab t1
join (select id, sum( IFNULL(n1,0)+ IFNULL(n2,0)+ IFNULL(n3,0)) as total
      from tab 
      group by id) t on t.id=t1.id
like image 26
Robert Avatar answered Sep 29 '22 06:09

Robert