Store Calculated Totals in Another Table

Sometimes a calculated value from one table must be stored in another table. First decide whether you are adding several columns in one row or aggregating several source rows; these are different operations.

Total several columns for each student

When each student is one row, add the subject columns directly; GROUP BY is not required.

INSERT INTO student3_total (s_id, mark)
SELECT id, math + social + science
FROM student3;

Store the average of several columns

INSERT INTO student3_total (s_id, mark)
SELECT id, (math + social + science) / 3
FROM student3;

When SUM() and GROUP BY are appropriate

If marks are stored as multiple exam rows per student, use SUM() with GROUP BY.

INSERT INTO student_total (student_id, total_mark)
SELECT student_id, SUM(mark) AS total_mark
FROM exam_marks
GROUP BY student_id;

Create a new result table

CREATE TABLE ... SELECT can create a result table directly. Alias calculated columns so the new column names are predictable.

CREATE TABLE student3_total AS
SELECT id AS s_id, (math + social + science) AS mark
FROM student3;

Display the stored total with student details

SELECT s.id, s.name, s.class, s.social, s.science, s.math, t.mark AS total_mark
FROM student3 AS s
INNER JOIN student3_total AS t ON t.s_id = s.id
ORDER BY s.id;
idnameclasssocialsciencemathtotal
2Max RuinThree855685226
3ArnoldThree554075170
4Krish StarFour605070180
5John MikeFour608090230
6Alex JohnFour559080225
7My John RobFifth786070208
8AsruidFive858090255
9Tes QrySix786070208
10Big JohnFour554055150

student3 SQL dump
student3_total SQL dump




Subscribe to our YouTube Channel here



plus2net.com
Mukesh

19-01-2019

i have some data , and want to sum Debit and Credit group by account id using select statement not do while or for next statement.
i want result in single line statement.
ACCOUNT NO. DATE PAYMENT_MODE(Debit/Credit) Amount
000001 01/01/2019 Debit 10000
000001 02/01/2019 Debit 20000
000001 03/01/2019 Credit 15000
000001 03/01/2019 Credit 10000

result
Account No Debit Credit
000001 30000 25000
smo1234

19-01-2019

Use Group by to sum based on PAYMENT_MODE(Debit/Credit) Amount.

SELECT ACCOUNT_NO, PAYMENT_MODE,SUM(PAYMENT_MODE ) as MODES FROM table_name WHERE ACCOUNT_NO='000001' GROUP BY PAYMENT_MODE

Read more on SQL SUM with GROUP Query

23-09-2019

Use Group by




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer