Here is an example of using the case function to complete this function
Case has two formats. Simple case function and case search function.
--Simple Case function
Case
Sex
When ' 1 ' then ' male '
When ' 2 ' Then ' woman '
Else ' other ' end
--case search function
case when sex = ' 1 ' Then ' man '
When sex = ' 2 ' Then ' female '
Else ' other '
end
In both of these ways, you can achieve the same functionality. The simple case function is relatively concise, but there are some limitations to the function, such as writing a judgment, compared with the search function.
There is also a problem to note that the case function returns only the first qualifying value, and the remainder of the case is automatically ignored.
For example, the following SQL, you can never get the "second class" result
Case when
col_1 in (' A ', ' B ') then ' first Class '
When Col_1 in (' a ') Then ' Class II '
Else ' other '
end
Let's look at some examples
Select Country,
sum (case when sex = ' 1 ' Then
Population else 0 end),--Male population
sum (case when sex = ' 2 ' Then
Population else 0 end)--female population
From Table_a
Group BY country;
Select sum (population),
Case Country
When ' China ' then ' Asia '
When ' India ' Then ' Asia '
When ' Japan ' then ' Asia '
When ' America ' Then ' North America '
When ' Canada ' then ' North America '
When ' Mexican ' then ' North America '
Else ' other ' end
From Table_a
Group BY Case Country
When ' China ' then ' Asia '
When ' India ' Then ' Asia '
When ' Japan ' then ' Asia '
When ' America ' Then ' North America '
When ' Canada ' then ' North America '
When ' Mexican ' then ' North America '
Else ' other ' end;
About Case Two
Select
Case if Salary <= then ' 1 '
when salary > Salary <= ' 2 '
When salary > Salary <= to Then ' 3 '
when salary > and salary <= 1000 ' 4 ' Then > Else null end Salary_class,
Count (*)
from table_a
Group by
Case when salary <= then ' 1 '
When salary > Salary <= Then ' 2 '
when salary > and Salary <= ' 3 ' br> When salary > I salary <= 1000 ' 4 '
else null end;