35, sql statement (case when then else end use) Details

Reproduced

Case has two formats. Case Case function and simple search function. 

- Simple Case function 
the CASE Sex 
         the WHEN '. 1' THEN 'M' 
         the WHEN '2' THEN 'F' 
the ELSE 'other' the END 

--Case search functions 
CASE WHEN sex = '1' THEN ' M' 
         the WHEN Sex = '2' THEN 'female' 
eLSE 'other' END 

both methods can achieve the same functionality.
Case wording simple function is relatively simple, but Case and search function compared to functional aspects will be some restrictions, such as writing predicate. 
There is also a need to pay attention to the problem, Case function returns only the first matching value, the rest of the Case section will be automatically ignored. 

For example, the following piece of SQL, you can never get a "second class" This result 
CASE WHEN col_1 IN ( 'a' , 'b') THEN ' first class' 
         the WHEN COL_1 the IN (' A ') THEN' second class' 
the eLSE 'other' END Here we look at using the Case function can do something.

A known data packets according to another embodiment, analysis.  

Case 1: The following data :( In order to see more clearly, I did not use the country code, but directly with the country name as a Primary Key) 
Country (country) population (population) 
China 600 
100 United States 
100 Canada 
United Kingdom 200 
France 300 
Japan 250 
200 Germany 
50 Mexico 
250 India, 

according to the country's demographic data, count the number of people in Asia and North America. You should obtain the following results. 
Population continent 
Asia 1100 
North America 250 
700 other 

want to solve this problem, how would you do? View a generation with the continent Code, it is a solution, but this is difficult to change the dynamics of the statistical approach. 
If you use the Case functions, SQL code is as follows: 
the SELECT SUM (Population), 
        the CASE Country 
                the WHEN 'China' THEN 'Asian' 
                the WHEN 'India' THEN 'Asian' 
                the WHEN 'Japan' THEN 'Asian' 
                the WHEN 'the United States' THEN 'North America' 
                WHEN 'Canada' THEN 'North America' 
                WHEN 'Mexico' THEN 'North America' 
        ELSE 'other' END 
the FROM Table_A 
the GROUP BY Country the CASE 
                WHEN 'China' THEN 'Asian' 
                WHEN 'India' THEN 'Asian' 
                WHEN 'Japan' THEN 'Asian' 
                WHEN 'the United States' THEN' North America ' 
                the WHEN' Canada 'THEN' North America ' 
                the WHEN' Mexico 'THEN' North America ' 
        eLSE' other 'END; 

case 2: Similarly, we can also use this method to determine the level of wages, and statistics for each class number. SQL code is as follows; 

the SELECT 
        the CASE the salary the WHEN <= 500 THEN '. 1' 
             the WHEN the salary> the salary the AND 500 <= 600 THEN '2' 












 














China 260 340 
45 55 Meiguo 
Jia Natai 51 49 
UK 40 60 

under ordinary circumstances, can also be achieved with the UNION query with a statement. But as consumption increases (Select two portions), and the SQL statement will be longer. 
The following is a Case function is to complete this function example of 

the SELECT Country, 
       the SUM (Sex = the WHEN the CASE '. 1' THEN 
                      Population the END the ELSE 0), - the male population of 
       the SUM (the WHEN the CASE Sex = '2' THEN 
                      Population the END the ELSE 0 ) - the female population 
the FROM Table_A 
the GROUP BY Country; 

we use Select, complete the form on the output of two-dimensional table, it shows strong Case function. 

Third, the use of the Case Check function.  

Use Case function in many cases are a very good solution at Check in. There may be many people simply do not Check, then I suggest you after reading the following examples also try to use Check in SQL. 

Let us give an example 
company A, the company has a rule, female staff salaries must be higher than 1000. And Case Check if it is expressed as follows 
CONSTRAINT check_salary CHECK 
           (The WHEN the CASE Sex = '2' 
                  THEN the WHEN the salary the CASE> 1000 
                        THEN the ELSE 0. 1 the END 
                  the ELSE the END =. 1. 1) 

if you want a Check, as shown 

CONSTRAINT check_salary the CHECK 
           (Sex = '2' the AND the salary> 1000) 

female staff actually in line with the conditions, you can not enter the male staff

 

Fourth, according to the selected conditions UPDATE.  

Embodiment, the following update condition 
wages of 5,000 or more employees wages reduced by 10% 
staff salary of between 2000 to 4600, a 15% increase wages 
readily conceivable choice is performed twice UPDATE statement, as follows 

-. 1 Condition 
UPDATE Personnel 
the SET salary = salary * 0.9 
the WHERE salary> = 5000; 
- conditions 2 
UPDATE Personnel 
the SET salary = salary * 1.15 
the WHERE salary> = 2000 the AND salary <4600; 

but things did not imagine so simple, assuming personal wages 5000. First, according to condition 1, 10% reduction in wages, salaries into 4500. Then run the second SQL time, because this man's 4500 salary is within the range of 2000-4600, the need to increase by 15%, and finally the man's wages result is 5175, not only did not decrease, but increased. If we turn to perform, then the wages of 4600 people opposite will turn reduce wages. For the time being no matter how absurd this rule is that if you want a SQL statement to achieve this, we need to use the Case function. Code is as follows: 

the UPDATE Personnel 
the SET = the CASE the WHEN the salary the salary> = 5000 
             THEN the salary 0.9 * 
the WHEN the salary> = the salary the AND 2000 <4600 
Salary * 1.15 THEN 
ELSE salary END; 

Here we must note that the last line ELSE salary is necessary, if not this line, do not meet these two conditions of people's wages will be written NUll, that would be something in the . The default value Else part in Case function is NULL, this is the place to note. 

This method can also use in many places, such as changing the primary key of this dirty work. 
Under normal circumstances, to the Primary key, a and b are two exchange data, need to go through the temporary store, copy, read back three process data, if using the Case function, then everything becomes much simpler. 
COL_1 COL_2 the p_key 
a Zhang. 1 
b Doe 2 
c 3 Wangwu 

assumed like data, the primary key needs to exchange a and b. With Case function to achieve it, as follows: 

the UPDATE SomeTable 
the SET the p_key = the CASE the WHEN the p_key = 'A' 
THEN 'B' 
the WHEN the p_key = 'B' 
THEN 'A' 
the ELSE the p_key the END 
the WHERE the p_key the IN ( 'A', 'B' ); 

the same may also be exchanged two Unique key. Note that, if the situation requires a primary key exchange takes place, most of the original design of this table will be enough place, it is recommended to check the adequacy of the design table. 

Fifth, the two tables to check whether the data is consistent. 

Unlike Case function DECODE function. In Case function may be used BETWEEN, LIKE, IS NULL, IN , EXISTS like. For example, the use of IN, EXISTS, can be sub-queries, in order to achieve more functionality. 

Mask example will be described next, there are two tables, tbl_A, tbl_B, keyCol table has two columns. Now we compare two tables, data tbl_A in keyCol column if the data can be found in keyCol column tbl_B, the return result 'Matched', if not found, returns the result 'Unmatched'. 
To achieve the following functions, can use the following two statements 

- IN time using 
the SELECT keycol, 
the CASE keycol the WHEN IN (the SELECT keycol the FROM tbl_B) 
THEN 'Matched' 
the ELSE 'Unmatched' the END the Label 
the FROM tbl_A; 

- when used EXISTS 
keycol the SELECT, 
the CASE the WHEN EXISTS (the FROM tbl_B the SELECT * 
the WHERE tbl_A.keyCol = tbl_B.keyCol) 
THEN 'Matched' 
the ELSE 'Unmatched' the END the Label 
the FROM tbl_A; 

results EXISTS iN and use are the same. You can also use NOT IN and NOT EXISTS, but this time to pay attention to NULL. 

Sixth, the use aggregate function in function Case 

Consider the following table a 
student number (std_id) program ID (class_id) Course name (class_name) Major In Flag (main_class_flg) 
100. 1 Economics the Y 
100 2 N history 
200 is N 2 History 
2003 archeology the Y- 
200 4 computer N 
300 4 computer N 
400 5 chemical N 
500 N 6 mathematics 

, some students chose the same time to repair several courses (100, 200) and some students choose only one course (300, 400). Students to take many courses, to choose a course as a major, major flag which writes Y. Choose only one course students majoring flag is N (in fact, if Y is written, then there would be no trouble following, in order, for example child, also please include). 
Now we have to follow the following two conditions on the table query 
only one elective course people, that returns the ID of course 
elective courses and more, returns the selected main course ID 

simple idea is that two different execution the SQL query statement. 
Condition 1 

- Condition 1: select only one course students 
the SELECT std_id, MAX (class_id) AS the Main_Class 
the FROM Studentclass 
the GROUP BY std_id 
the HAVING COUNT (*) = 1; 

The results of 1 

STD_ID MAIN_CLASS 
------ ---------- 
300 4 
400 5 
500 6 

Condition 2 

- Condition 2: many courses students choose 
the SELECT std_id, AS class_id the Main_Class 
the FROM Studentclass 
the WHERE main_class_flg = 'Y'; 

results of 2 

STD_ID MAIN_CLASS 
------ ---------- 
100. 1 
200 is. 3 

If Case function, an SQL statement as long as we can solve the problem, as shown below 

SELECT std_id, 
the cASE the WHEN COUNT (*) =. 1 - select only a course where students 
THEN MAX (class_id) 
the ELSE MAX (the WHEN main_class_flg the cASE = 'the Y' 
THEN class_id 
the ELSE NULL the END 

the END the AS the Main_Class 
the FROM Studentclass 
GROUP BY std_id; 

run results 

STD_ID MAIN_CLASS 
------ ---------- 
100. 1 
200 is. 3 
300. 4 
400. 5 
500. 6 

nested function Case Case function, a sum function in the Case function and other methods, we can easily solve this problem. Use Case function gives us greater freedom. 
Finally, a reminder to use for novice Case function careful not to commit the following mistakes 

the CASE COL_1 
1 THEN 'Right' the WHEN 
'Wrong' the WHEN NULL THEN 
END 

circumstances in this statement When Null This line always returns unknown, it will never appear in the Wrong . Because the sentence can be replaced WHEN col_1 = NULL, this is a wrong usage, this time we should choose to use IS NULL WHEN col_1.

-----------------

Example 1:

Use the query results iFavoriteID, iFavUserType, cUser, iArticleID, dFavoriteTime five field values:

the SELECT iFavoriteID,
the CASE the WHEN iFavUserType = 0 THEN 'news administrator'
the WHEN = 1 THEN iFavUserType 'business'
the WHEN iFavUserType = 2 THEN' Member '
the WHEN = iFavUserType. 3 THEN' Unregistered '
the WHEN iFavUserType. 4 = the then' anonymous'
the END iFavUserType the AS, CUser, iArticleID,
the CONVERT (nvarchar (100), dFavoriteTime, 111) the FROM dig_favorite the AS dFavoriteTime

Example 2:

The CASE MEMBERTYPE` the WHEN = `the SELECT. 1
THEN 'team members'
the ELSE 'Supervisor'
the END the FROM` tab_sign_member`
the WHERE. 1

--------------------------------------------

Here you illustrates the use of three methods mysql statement in the case when, for your reference study, if you are mysql interested in the case when the use of statements, may wish to have a look.

1、

  1. select name,  
  2.  case   
  3.         when birthday<'1981' then 'old'  
  4.         when birthday>'1988' then 'yong'  
  5.         else 'ok' END YORN  
  6. from lee; 

2、

  1. select NAME,  
  2.  case name  
  3.      when 'sam' then 'yong'  
  4.         when 'lee' then 'handsome'  
  5.         else 'good' end  
  6. from lee; 

Of course, the case when statements can be complex

3、

  1. select name,birthday,  
  2.  case   
  3.      when birthday>'1983' then 'yong'  
  4.         when name='lee' then 'handsome'  
  5.         else 'just so so ' end  
  6. from lee;  
  7.  

The above is introduced using the example of the case when mysql statement.

Published 38 original articles · won praise 5 · Views 6014
Reproduced

Case具有两种格式。简单Case函数和Case搜索函数。 

——简单Case函数 
CASE sex 
         WHEN '1' THEN '男' 
         WHEN '2' THEN '女' 
ELSE '其他' END 

——Case搜索函数 
CASE WHEN sex = '1' THEN '男' 
         WHEN sex = '2' THEN '女' 
ELSE '其他' END 

这两种方式,可以实现相同的功能。
简单Case函数的写法相对比较简洁,但是和Case搜索函数相比,功能方面会有些限制,比如写判断式。 
还有一个需要注意的问题,Case函数只返回第一个符合条件的值,剩下的Case部分将会被自动忽略。 

比如说,下面这段SQL,你永远无法得到“第二类”这个结果 
CASE WHEN col_1 IN ( 'a', 'b') THEN '第一类' 
         WHEN col_1 IN ('a')       THEN '第二类' 
ELSE'其他' END  下面我们来看一下,使用Case函数都能做些什么事情。 

一,已知数据按照另外一种方式进行分组,分析。 

案例1:有如下数据:(为了看得更清楚,我并没有使用国家代码,而是直接用国家名作为Primary Key) 
国家(country) 人口(population) 
中国 600 
美国 100 
加拿大 100 
英国 200 
法国 300 
日本 250 
德国 200 
墨西哥 50 
印度 250 

根据这个国家人口数据,统计亚洲和北美洲的人口数量。应该得到下面这个结果。 
大洲 人口 
亚洲 1100 
北美洲 250 
其他 700 

想要解决这个问题,你会怎么做?生成一个带有洲Code的View,是一个解决方法,但是这样很难动态的改变统计的方式。 
如果使用Case函数,SQL代码如下: 
SELECT  SUM(population), 
        CASE country 
                WHEN '中国'     THEN '亚洲' 
                WHEN '印度'     THEN '亚洲' 
                WHEN '日本'     THEN '亚洲' 
                WHEN '美国'     THEN '北美洲' 
                WHEN '加拿大'  THEN '北美洲' 
                WHEN '墨西哥'  THEN '北美洲' 
        ELSE '其他' END 
FROM    Table_A 
GROUP BY CASE country 
                WHEN '中国'     THEN '亚洲' 
                WHEN '印度'     THEN '亚洲' 
                WHEN '日本'     THEN '亚洲' 
                WHEN '美国'     THEN '北美洲' 
                WHEN '加拿大'  THEN '北美洲' 
                WHEN '墨西哥'  THEN '北美洲' 
        ELSE '其他' END; 

案例2:同样的,我们也可以用这个方法来判断工资的等级,并统计每一等级的人数。SQL代码如下; 

SELECT 
        CASE WHEN salary <= 500 THEN '1' 
             WHEN salary > 500 AND salary <= 600  THEN '2' 
             WHEN salary > 600 AND salary <= 800  THEN '3' 
             WHEN salary > 800 AND salary <= 1000 THEN '4' 
        ELSE NULL END salary_class, 
        COUNT(*) 
FROM    Table_A 
GROUP BY 
        CASE WHEN salary <= 500 THEN '1' 
             WHEN salary > 500 AND salary <= 600  THEN '2' 
             WHEN salary > 600 AND salary <= 800  THEN '3' 
             WHEN salary > 800 AND salary <= 1000 THEN '4' 
        ELSE NULL END; 

二,用一个SQL语句完成不同条件的分组。 

有如下数据 
国家(country) 性别(sex) 人口(population) 
中国 1 340 
中国 2 260 
美国 1 45 
美国 2 55 
加拿大 1 51 
加拿大 2 49 
英国 1 40 
英国 2 60 

按照国家和性别进行分组,得出结果如下 
国家 男 女 
中国 340 260 
美国 45 55 
加拿大 51 49 
英国 40 60 

普通情况下,用UNION也可以实现用一条语句进行查询。但是那样增加消耗(两个Select部分),而且SQL语句会比较长。 
下面是一个是用Case函数来完成这个功能的例子 

SELECT country, 
       SUM( CASE WHEN sex = '1' THEN 
                      population ELSE 0 END),  --男性人口 
       SUM( CASE WHEN sex = '2' THEN 
                      population ELSE 0 END)   --女性人口 
FROM  Table_A 
GROUP BY country; 

这样我们使用Select,完成对二维表的输出形式,充分显示了Case函数的强大。 

三,在Check中使用Case函数。 

在Check中使用Case函数在很多情况下都是非常不错的解决方法。可能有很多人根本就不用Check,那么我建议你在看过下面的例子之后也尝试一下在SQL中使用Check。 

下面我们来举个例子 
公司A,这个公司有个规定,女职员的工资必须高于1000块。如果用Check和Case来表现的话,如下所示 
CONSTRAINT check_salary CHECK 
           ( CASE WHEN sex = '2' 
                  THEN CASE WHEN salary > 1000 
                        THEN 1 ELSE 0 END 
                  ELSE 1 END = 1 ) 

如果单纯使用Check,如下所示 

CONSTRAINT check_salary CHECK 
           ( sex = '2' AND salary > 1000 ) 

女职员的条件倒是符合了,男职员就无法输入了

Guess you like

Origin blog.csdn.net/luluisntlulu/article/details/100579958