0

Is it possible to sum up values in mysql as in excel? I´m currently trying query below but it sums up the values on another rows. I need something that wil be working like sum function in excel and if I add some values into the table, the values will summed in the column (spolu) automatically.

INSERT INTO test (spolu)
SELECT SUM(hodnota1+hodnota2)
FROM test
GROUP BY id

This query do this:

This query do this:

but i need this:

enter image description here

2
  • 1
    Redundancy generally is not a good idea. Why don't select the sum when it need? Commented Oct 26, 2015 at 12:54
  • 1
    you actualy want to update a column in that case:UPDATE test SET spolu = hodnota1 + hodnota2 should work for you. Commented Oct 26, 2015 at 13:06

2 Answers 2

1

You need simple +:

SELECT id, hodnota1, hodnota2, hodnota1 +  hodnota2 AS spolu
FROM test;

For automatic calculating you need to use trigger or generated column.

Generated columns 5.7+

CREATE TABLE test(
  id INT PRIMARY KEY AUTO_INCREMNET,
  hodnota1 INT,
  hodnota2 INT,
  spolu INT AS (hodnota1 + hodnota2)
);

Another way is to create view:

CREATE VIEW vw_test
AS
SELECT id, hodnota1, hodnota2, hodnota1 +  hodnota2 AS spolu
FROM test;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir this works. Could please little bit more explain trigger or computed column?
0

This should work, if you need it as a table, you could create a view with this output.

SELECT id, hodnota1, hodnota2, 
SUM(hodnota1, hodnota2) AS spolu
FROM test;
GROUP BY id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.