SQL statement-case when then else end, SQL-case

Source: Internet
Author: User

SQL statement-case when then else end, SQL-case

Output the following results based on the preceding table information:



The following are the database and table structure data:

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);

Execute the SQL statement:

Mysql> select deptID as 'department ', sum (case SubjMonth when 1 then sales end) 'January sales end', sum (case SubjMonth when 2 then sales end) 'February sales end ', sum (case SubjMonth when 3 then sales end) 'October sales', sum (case SubjMonth when 4 then sales end) 'October sales' from deptsales d group by deptID; + ------ + ------------ + | Department | sales in December | + ------ + ------------ + | 1 | 55 | NULL | 2 | 66 | 34 | NULL | 3 | 77 | NULL | 78 | NULL | 4 | NULL | 56 | NULL | + ------ + ------------ + 4 rows in set



Case whenthenelseend

In case of XXX, if XXX fails, XXX ends.
Case when ...... Then ...... Else ...... End

Case whenthenelseend)

Select ByeTime, case when len (ByeTime)> 0 then str (DATEDIFF (day, ComeInTime, ByeTime) + '(resigned )'
Else str (DATEDIFF (day, ComeInTime, getdate () end as test
From myUser where DelFlag = '0' and UserID = 'cq'
Try this. The syntax should be correct.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.