I have 2 table grade and tb_category
CREATE TABLE `grade` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`studentid` int(11) DEFAULT NULL,
`category` varchar(100) DEFAULT NULL,
`grade` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO `grade` (`id`, `studentid`, `category`, `grade`) VALUES
(1, 1, 'PAS', 76),
(2, 1, 'PTS', 100),
(3, 2, 'PAS', 100),
(4, 3, 'PTS', 100),
(5, 4, 'PTS', 100),
(6, 4, 'PAS', 100);
CREATE TABLE `tb_category` (
`gradecatid` int(11) NOT NULL DEFAULT 0,
`code` varchar(3) DEFAULT NULL,
`category_name` varchar(200) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;
INSERT INTO `tb_category` (`gradecatid`, `code`, `category_name`) VALUES
(1, 'PTS', 'Mid-Semester'),
(2, 'PAS', 'End Semester');
with data:
id studentid category grade
1 1 PAS 76
2 1 PTS 100
3 2 PAS 100
4 3 PTS 100
5 4 PTS 100
6 4 PAS 100
gradecatid code category_name
1 PTS Mid-Semester
2 PAS End Semester
the expect result is dynamic column base on category column
studentid | PAS | PTS |
---|---|---|
1 | 76 | 100 |
2 | 100 | 0 |
3 | 0 | 100 |
4 | 100 | 100 |
I have the query for result
SELECT studentid,
SUM(IFNULL(IF(category = 'PAS', grade, 0), 0)) AS grade1,
SUM(IFNULL(IF(category = 'PTS', grade, 0), 0)) AS grade2
FROM `grade`
group by studentid
the user can add or delete the category (PAS, PTS), so above query will not work if there's any changes with the category, every user can have multiple category, is it possible to have dynamic column based on the user?
studentid | grade1 | grade2 | grade3 | grade4 |
---|---|---|---|---|
1 | 76 | 100 | ? | ? |
2 | 100 | 0 | ? | ? |
3 | 0 | 100 | ? | ? |
4 | 100 | 100 | ? | ? |