Basically learned the next SQL function statement, case when similar to the C language in the Switich cases statement, multi-branch selection, different values can have a different amount of return. For example, in a table that contains a sex field, the possible value is 1, 2, and after the subordinate statement is executed, a value of 1 returns the male, where the value is 2 to return the female.
--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
At the same time, case statements are implemented in two ways. The following tables are available:
Country (country) |
Population (population) |
China |
600 |
United States |
100 |
Canada |
100 |
United Kingdom |
200 |
France |
300 |
Japan |
250 |
Germany |
200 |
Mexico |
50 |
India |
250 |
Now to count the number of people on each continent, you can use the following statement:
SELECT SUM (population), case country when ' China ' Then ' Asia ' when ' India ' then ' Asia ' when ' Japan ' Then ' Asia ' When ' us ' then ' North America ' when ' Canada ' Then ' North America ' when ' Mexico ' then ' North America ' Else ' other ' endfrom Table_agroup by case country when ' China ' then ' Asia ' when ' India ' then ' Asia ' when ' Japan ' then ' Asia ' C22/>when ' Us ' then ' North America ' when ' Canada ' then ' North America ' when ' Mexico ' then ' North America ' else ' other ' END;
The test code and results for SQLite data tables in Sqliteman are as follows:
Similarly, the method can be used to determine the number of countries on each continent, the code and results are as follows:
Here, sum (perosn) sums the number of people in each continent and returns the total number of values (total); count (perosn) counts the number of countries on each continent, returning the number of rows that match the specified criteria.
Refer to the above Information section from: https://www.cnblogs.com/prefect/p/5746624.html
Case of SQL when