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?
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.
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.
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.
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...
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With