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