SQL PHP HTML ASP JavaScript articles and free scripts to download
 

Calculating and storing SUM of a column in another table

Some time we have to collect the SUM , AVG or any other type of data from one table and store them in another table. Say for example we want to store sum of all marks of each student in a different table. We conducted different exams for students and now we will be adding all the marks for each student and store them in a different table. We will be using GROUP BY command to find out sum of all the marks or each student. Here is the SQL to do this.

insert into s_mark(s_id,mark) select s_id, sum(test1) from s_test group by s_id

The above query will total all marks of each student and then store them in s_marks table. You can use AVG, MAX,MIN commands in place of SUM command to get desire result. Here is the one for AVG marks

insert into s_mark(s_id,mark) select s_id, AVG(test1) from s_test group by s_id

Here are our both tables for you.
CREATE TABLE `s_mark` (
  `s_id` int(3) NOT NULL,
  `mark` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- 
-- Dumping data for table `s_mark`
-- 
INSERT INTO `s_mark` VALUES (1, 7);
INSERT INTO `s_mark` VALUES (2, 6);
-- ----------------------------------
-- 
-- Table structure for table `s_test`
-- 
CREATE TABLE `s_test` (
  `s_id` int(3) NOT NULL,
  `test1` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;



Further readings
Changing structur of the table bu alter query
Create table query with if exists sql with php script
Creating a new table by using data from one table
Change the name of a table
Copying data from one table to another table
Delete records from a table with conditinos
Delete table by using DROP sql
Updating another table with data from main table
Update SQL commands
Inserting SUM, AVG data from one table column to other using group by command
Table Records are downloaded as .csv file
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked

Join Our Email List
Email:  
For Email Newsletters you can trust
Modify Table
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2013 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer