Mysql將近兩個月的記錄合并為一行顯示

來源:互聯網
上載者:User

標籤:

最近做報表統計,用到要求把近兩個月的績效作比較,並作出一些環比資料等。

情境:將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。

 

Mysql將近兩個月的記錄合并為一行顯示

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.