Sql語句-case when then else end,sql-case

來源:互聯網
上載者:User

Sql語句-case when then else end,sql-case

根據上面的表資訊輸出下面的結果:



下面是建庫和表結構據:

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 whenthenelseend) 詳細解釋

遇到 XXX情況 就 XXX 遇不到就 XXX 結束
case when …… then …… else …… end
 
SQL條件控制(case whenthenelseend)

select ByeTime,case when len(ByeTime)>0 then str(DATEDIFF(day,ComeInTime,ByeTime))+'(已離職)'
else str(DATEDIFF(day,ComeInTime,getdate())) end as test
from myUser where DelFlag='0' and UserID='cq'
這樣試一下.文法應該沒有問題
 

相關文章

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.