最近做報表統計,用到要求把近兩個月的績效作比較,並作出一些環比資料等。
場景:將1班同學的兩個月的語文的平均成績合併到一行比較。
CREATE TABLE `Chinese_score` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`score` int(11),
`date` varchar(6),
PRIMARY KEY (`id`)
)
插入幾條同學們兩個月的成績:
mysql> insert into chinese_score value(null,'張三',91,'201506');
mysql> insert into chinese_score value(null,'李四',88,'201506');
mysql> insert into chinese_score value(null,'老王',80,'201506');
mysql> insert into chinese_score value(null,'祥子',77,'201506');
mysql> insert into chinese_score value(null,'張三',89,'201507');
mysql> insert into chinese_score value(null,'李四',85,'201507');
mysql> insert into chinese_score value(null,'老王',79,'201507');
mysql> insert into chinese_score value(null,'祥子',82,'201507');
查詢近兩個月的語文平均成績和總成績作比較:
mysql> select avg(if(date='201506',score,null)) avg06, avg(if(date='201507',score,null)) avg07, sum(if(date='201506',score,null)) sum06, sum(if(date='201507',score,null)) sum07 from chinese_score;
+---------+---------+-------+-------+
| avg06 | avg07 | sum06 | sum07 |
+---------+---------+-------+-------+
| 84.0000 | 83.7500 | 336 | 335 |
+---------+---------+-------+-------+
1 row in set
avg(if(date='201506',score,null))的效果等於:
if():如果date的值為201506,那麼將這條記錄的score加入到avg(score)中,否則為null。