Case-when statement in SQL

Source: Internet
Author: User

1. In the WHERE clause:

  1  create TABLE ' hello '. ' Sometbl ' ( Span style= "color: #008080;" > 2   3   ' id ' INT not NULL auto_increment,   5   6   7   ' B ' VARCHAR NULL,   8   9   ' C ' VARCHAR NULL,  10  11   PRIMARY KEY (' id '),  12  13  UNIQUE INDEX ' Id_unique ' (' id ' ASC); 
1 INSERT  into' Hello '. ' Sometbl ' (' A ', ' B ', ' C ')VALUES('1','1','0');2 3 INSERT  into' Hello '. ' Sometbl ' (' B ', ' C ')VALUES('1','1');4 5 INSERT  into' Hello '. ' Sometbl ' (' A ', ' C ')VALUES('1','1');6 7 INSERT  into' Hello '. ' Sometbl ' (' B ')VALUES('1');

There are two records in query a,b,c that meet the =1 criteria

SELECT *  fromHello.sometblwhere(( Case  whenA='1'  Then 1 Else 0 End)+( Case  whenB='1'  Then 1 Else 0 End)+( Case  whenC='1'  Then 1 Else 0 End))=2;

2. In select as a column

Output when ID 1,2,3,4, one, two, three, four

SELECTId Case  whenId=1  Then 'a' whenId=2  Then 'two' whenId=3  Then 'three' whenId=4  Then 'Four'Else 'other' EndChinese numerals fromHELLO.SOMETBL;

Output

Case-when statement in SQL

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.