最近做报表统计,用到要求把近两个月的绩效作比较,并作出一些环比数据等。
场景:将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。