码迷,mamicode.com
首页 > 数据库 > 详细

Sql语句-case when then else end

时间:2014-08-26 17:21:36      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:sql语句-case when then

bubuko.com,布布扣

根据上面的表信息输出下面的结果:

bubuko.com,布布扣


下面是建库和表结构据:

create table DeptSales
(
	deptID int,
	SubjMonth int ,
	sales int ,
	deptname varchar(50)
)

insert into deptsales (deptid ,subjmonth,sales) values (1,1,55);
insert into deptsales (deptid ,subjmonth,sales) values (2,1,66);
insert into deptsales (deptid ,subjmonth,sales) values (3,1,77);
insert into deptsales (deptid ,subjmonth,sales) values (2,2,34);
insert into deptsales (deptid ,subjmonth,sales) values (4,2,56);
insert into deptsales (deptid ,subjmonth,sales) values (3,3,78);

执行sql语句:

mysql> select deptID as '部门',sum(case SubjMonth when 1 then sales end) '一月销售额',sum(case SubjMonth when 2 then sales end) '二月销售额',sum(case SubjMonth when 3 then sales end) '三月销售额',sum(case SubjMonth when 4 then sales end) '四月销售额'  from deptsales d group by deptID;
+------+------------+------------+------------+------------+
| 部门 | 一月销售额 | 二月销售额 | 三月销售额 | 四月销售额 |
+------+------------+------------+------------+------------+
|    1 | 55         | NULL       | NULL       | NULL       |
|    2 | 66         | 34         | NULL       | NULL       |
|    3 | 77         | NULL       | 78         | NULL       |
|    4 | NULL       | 56         | NULL       | NULL       |
+------+------------+------------+------------+------------+
4 rows in set


Sql语句-case when then else end

标签:sql语句-case when then

原文地址:http://blog.csdn.net/benjamin_whx/article/details/38850237

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!