|
| |
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;
| |
|
|
|