MySQL If--else

Source: Internet
Author: User

Case has two formats. Simple case function and case search function.

--Simple case function when '  1 ' then ' Male ' when  ' 2 ' Then ' Women '  Else ' other ' end--case search function case when sex = ' 1 ' Then ' Man ' 
   
    when sex = ' 2 ' Then ' women ' else '     other ' end  
   

In both of these ways, the same functionality can be achieved. The simple case function is relatively concise, but there are some limitations to the function, such as writing a decision, compared to the search function.

There is also a problem to focus on, the case function returns only the first qualifying value, and the remaining case section is automatically ignored.

--for example, the following SQL, you can never get the result of a "second class" When the case is col_1 in (' A ', ' B ') then ' first Class ' When     col_1 in (' a ') Then ' second '     Else ' other ' end  

The following example shows:

3. Combining sum with case can be used to achieve segmented statistics.
If you now want to count the number of genders in the table above, the SQL statement is as follows:

Sql> Select  2    sum (case u.sex if 1 then 1 else 0 end) male,  3    sum (case u.sex while 2 then 1 else 0 end) female,  4    sum (case time U.sex <>1 and u.sex<>2 then 1 else 0 end) gender is null  5 from  users u;         Male         female       sex is empty------------------------------         3          2          0--------------------------------------- -----------------------------------------sql> Select  2    count (case if U.sex=1 then 1 end) male,  3    count (case time u.sex=2 then 1 end) female,  4    count (case time U.sex <>1 and u.sex<>2 then 1 end) Sex is empty  5 from  users u;         Male          female       sex is empty------------------------------         3          2          0

MySQL If--else

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.