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.
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;
INSERT INTO student3_total (s_id, mark)
SELECT id, (math + social + science) / 3
FROM student3;
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 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;
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;
| id | name | class | social | science | math | total |
|---|---|---|---|---|---|---|
| 2 | Max Ruin | Three | 85 | 56 | 85 | 226 |
| 3 | Arnold | Three | 55 | 40 | 75 | 170 |
| 4 | Krish Star | Four | 60 | 50 | 70 | 180 |
| 5 | John Mike | Four | 60 | 80 | 90 | 230 |
| 6 | Alex John | Four | 55 | 90 | 80 | 225 |
| 7 | My John Rob | Fifth | 78 | 60 | 70 | 208 |
| 8 | Asruid | Five | 85 | 80 | 90 | 255 |
| 9 | Tes Qry | Six | 78 | 60 | 70 | 208 |
| 10 | Big John | Four | 55 | 40 | 55 | 150 |
student3 SQL dump
student3_total SQL dump
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| 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 | |