warnerst
warnerst

Reputation: 211

sum across a row in sql

I want to sum the values of Punten1,Punten 2,Punten 3,Punten4 as a total. But I only know how to sum the values across the column. But not across the row. Does anyone know how to do this.

SELECT Punten1, Punten2, Punten3, Punten4
Punten1 + Punten 2 + Punten3 + Punten4 as Puntentotaal
FROM puntentotaal

So i would like to sum the values of Punten1,Punten 2,Punten 3,Punten4 in a new column: puntentotaal thanks!

Upvotes: 5

Views: 23259

Answers (2)

Govil
Govil

Reputation: 2054

SELECT Punten1, Punten2, Punten3, Punten4, 
Punten1 + Punten2 + Punten3 + Punten4 as Puntentotaal
FROM puntentotaal;

just an extra comma. I am assuming your table as unique ID as a column.

UPDATE puntentotaal AS t1 INNER JOIN puntentotaal AS t2 SET t1.Puntentotaal = 
(t2.Punten1 + t2.Punten2 + t2.Punten3 + t2.Punten4) where t1.ID = t2.ID;

This will update the sum of Punten1,Punten 2,Punten 3,Punten4 in column Puntentotaal in all the rows.

Upvotes: 6

Minesh
Minesh

Reputation: 2302

Your question titles as "sum across row" but what you are trying to achieve is sum across column.

If you are looking for "sum across row" there is function called SUM(field_name) which will give you sum of specific field for all the rows selected, you can use this function with GROUP BY

If you are looking for "sum across column" you are doing it right with + sign, just need to add comma as per @paul suggested.

Upvotes: 2

Related Questions