当前位置:网站首页>[sql] case expression
[sql] case expression
2022-07-26 02:57:00 【wy_ hhxx】
《SQL Advanced tutorial 》 MICK 1-1 CASE expression note
About... For creating tables for examples SQL Statements and sample code , Please refer to the following website .
http://www.ituring.com.cn/book/1813( Please click on “ Download with book ” Download relevant materials in Chinese )
---------------------------------------------------------------
explain : The tests in the following notes are based on postgresql14
Command line connection local PSQL: psql -U <username> -d <dbname> -h 127.0.0.1 -W
Catalog
Two ways of writing : Simple CASE expression 、 Search for CASE expression
Change the existing number into a new way and count
Use one SQL Statement for different condition statistics
stay UPDATE Conditional branching in a statement
CASE Expression Overview
Two ways of writing : Simple CASE expression 、 Search for CASE expression
-- Simple CASE expression
CASE sex
WHEN '1' THEN ' male '
WHEN '2' THEN ' Woman '
ELSE ' other ' END
-- Search for CASE expression
CASE WHEN sex ='1' THEN ' male '
WHEN sex ='2' THEN ' Woman '
ELSE ' other ' ENDUse CASE Note on expressions
matters needing attention 1: Use WHEN Clause should pay attention to the exclusivity of conditions
Found to be true WHEN When clause ,CASE The true or false value judgment of the expression will be suspended , remainder WHEN Clause is ignored .
matters needing attention 2: Unify the data types returned by each branch
matters needing attention 3: Don't forget to write END
matters needing attention 4: Develop writing ELSE The habit of clauses
Don't write ELSE When clause ,CASE The result of the expression is NULL.
Change the existing number into a new way and count

PopTbl Create table command
/* Convert the existing numbering method into a new one and make statistics */
CREATE TABLE PopTbl
(pref_name VARCHAR(32) PRIMARY KEY,
population INTEGER NOT NULL);
INSERT INTO PopTbl VALUES(' Tokushima ', 100);
INSERT INTO PopTbl VALUES(' Xiangchuan ', 200);
INSERT INTO PopTbl VALUES(' Ehime ', 150);
INSERT INTO PopTbl VALUES(' Gao Zhi ', 200);
INSERT INTO PopTbl VALUES(' Fukuoka, ', 300);
INSERT INTO PopTbl VALUES(' Saga ', 100);
INSERT INTO PopTbl VALUES(' Nagasaki ', 200);
INSERT INTO PopTbl VALUES(' Tokyo ', 400);
INSERT INTO PopTbl VALUES(' Herd horses ', 50);PopTbl The contents are as follows
test=> select * from Poptbl;
pref_name | population
-----------+------------
Tokushima | 100
Xiangchuan | 200
Ehime | 150
Gao Zhi | 200
Fukuoka, | 300
Saga | 100
Nagasaki | 200
Tokyo | 400
Herd horses | 50
(9 rows)
test=>First look at the following CASE Statement output result
test=> SELECT CASE pref_name
WHEN ' Tokushima ' THEN ' Four countries '
WHEN ' Xiangchuan ' THEN ' Four countries '
WHEN ' Ehime ' THEN ' Four countries '
WHEN ' Gao Zhi ' THEN ' Four countries '
WHEN ' Fukuoka, ' THEN ' Kyushu '
WHEN ' Saga ' THEN ' Kyushu '
WHEN ' Nagasaki ' THEN ' Kyushu '
ELSE ' other ' END AS district
FROM PopTbl;
district
----------
Four countries
Four countries
Four countries
Four countries
Kyushu
Kyushu
Kyushu
other
other
(9 rows)
test=> 【 example 】 Convert the county number to the district number
test=> SELECT CASE pref_name
test-> WHEN ' Tokushima ' THEN ' Four countries '
test-> WHEN ' Xiangchuan ' THEN ' Four countries '
test-> WHEN ' Ehime ' THEN ' Four countries '
test-> WHEN ' Gao Zhi ' THEN ' Four countries '
test-> WHEN ' Fukuoka, ' THEN ' Kyushu '
test-> WHEN ' Saga ' THEN ' Kyushu '
test-> WHEN ' Nagasaki ' THEN ' Kyushu '
test-> ELSE ' other ' END AS district,
test-> SUM(population)
test-> FROM PopTbl
test-> GROUP BY CASE pref_name
test-> WHEN ' Tokushima ' THEN ' Four countries '
test-> WHEN ' Xiangchuan ' THEN ' Four countries '
test-> WHEN ' Ehime ' THEN ' Four countries '
test-> WHEN ' Gao Zhi ' THEN ' Four countries '
test-> WHEN ' Fukuoka, ' THEN ' Kyushu '
test-> WHEN ' Saga ' THEN ' Kyushu '
test-> WHEN ' Nagasaki ' THEN ' Kyushu '
test-> ELSE ' other ' END;
district | sum
----------+-----
Kyushu | 600
Four countries | 650
other | 450
(3 rows)
test=>GROUP BY The last paragraph can also be written district, as follows
test=> SELECT CASE pref_name
WHEN ' Tokushima ' THEN ' Four countries '
WHEN ' Xiangchuan ' THEN ' Four countries '
WHEN ' Ehime ' THEN ' Four countries '
WHEN ' Gao Zhi ' THEN ' Four countries '
WHEN ' Fukuoka, ' THEN ' Kyushu '
WHEN ' Saga ' THEN ' Kyushu '
WHEN ' Nagasaki ' THEN ' Kyushu '
ELSE ' other ' END AS district,
SUM(population)
FROM PopTbl
GROUP BY district;
district | sum
----------+-----
Kyushu | 600
Four countries | 650
other | 450
(3 rows)
test=>explain : there GROUP BY Clause uses exactly SELECT The nickname of the column defined in the clause district. But strictly speaking , This kind of writing is against the standard SQL Of the rules . because GROUP BY Clause ratio SELECT Statement first , So in GROUP BY Clause refers to in SELECT The nickname defined in clause is not allowed . in fact , stay Oracle、DB2、SQL Server When this method is used in the database, it will make mistakes . But there is also support for this SQL Statement database , For example, in PostgreSQL and MySQL in , This query statement can be executed smoothly .
Use one SQL Statement for different condition statistics

/* Use one SQL Statement to make statistics of different conditions */
SELECT pref_name,
/* Male population */
SUM( CASE WHEN sex = '1' THEN population ELSE 0 END) AS cnt_m,
/* Female population */
SUM( CASE WHEN sex = '2' THEN population ELSE 0 END) AS cnt_f
FROM PopTbl2
GROUP BY pref_name;test-> GROUP BY pref_name;
pref_name | cnt_m | cnt_f
-----------+-------+-------
Nagasaki | 125 | 125
Gao Zhi | 100 | 100
Saga | 20 | 80
Tokyo | 250 | 150
Xiangchuan | 100 | 100
Ehime | 100 | 50
Tokushima | 60 | 40
Fukuoka, | 100 | 200
(8 rows)
test=>
stay UPDATE Conditional branching in a statement

Suppose you need to update the data of this table according to the following conditions .
1. Yes, the current salary is 30 Employees above 10000 yen , A pay cut 10%.
2. Yes, the current salary is 25 More than 10000 yen and dissatisfied 28 Million yen employees , A raise 20%.
The updated data according to these requirements should be as shown in the following table .

Be careful : You cannot use two in turn UPDATE Sentence completion , Because the second one UPDATE The statement will be based on the first UPDATE Result operation after statement update .
Salaries Create table statement
/* Employee salary information table */
CREATE TABLE Salaries
(name VARCHAR(32) PRIMARY KEY,
salary INTEGER NOT NULL);
INSERT INTO Salaries VALUES(' Xiangtian ', 300000);
INSERT INTO Salaries VALUES(' Shenqi ', 270000);
INSERT INTO Salaries VALUES(' Wooden village ', 220000);
INSERT INTO Salaries VALUES(' saito ', 290000);The update statement is as follows
/* use CASE Write the correct update operation in the expression */
UPDATE Salaries
SET salary = CASE WHEN salary >= 300000
THEN salary * 0.9
WHEN salary >= 250000 AND salary < 280000
THEN salary * 1.2
ELSE salary END;
边栏推荐
- What if the test / development programmer gets old? Lingering cruel facts
- 重装Win7系统如何进行?
- Keil's operation before programming with C language
- Eslint common error reporting set
- [steering wheel] use the 60 + shortcut keys of idea to share with you, in order to improve efficiency (live template & postfix completion)
- Arthas download and startup
- Application of shift distance and hypothesis
- [SQL] 自连接的用法
- 朋友刚学完自动化测试就拿25Koffer,我功能测试何时才能到头?
- Information System Project Manager - Chapter 10 communication management and stakeholder management examination questions over the years
猜你喜欢

C language -- program environment and preprocessing

ES6高级-利用构造函数继承父类属性

如何有效的去防止别人穿该网站首页快照

FPGA_Vivado软件初次使用流程_超详细

Self-supervised learning method to solve the inverse problem of Fokker-Planck Equation

Standardize your own debug process

图像识别(七)| 池化层是什么?有什么作用?

AMD64(x86_64)架构abi文档:中

Stack Title: the longest absolute path of a file

移位距离和假设的应用
随机推荐
【方向盘】工具提效:Sublime Text 4的常用快捷键合集
Skill list of image processing experts
Arthas view the source code of the loaded class (JAD)
[reading notes] user portrait methodology and engineering solutions
【方向盘】使用IDEA的60+个快捷键分享给你,权为了提效(重构篇)
从各大APP年度报告看用户画像——标签,比你更懂你自己
.net serialize enumeration as string
Arthas download and startup
el-table 表头合并前四列,合并成一个单元格
Longest Substring Without Repeating Characters
OxyCon 2022 网络抓取前沿大会即将开启!
[C] Explain language file operation in detail
移位距离和假设的应用
【方向盘】使用IDEA的60+个快捷键分享给你,权为了提效(Live Template&Postfix Completion篇)
Is it safe to open galaxy securities account by mobile phone?
这种动态规划你见过吗——状态机动态规划之股票问题(上)
ES6 advanced - inherit parent class attributes with constructors
Information system project managers must recite the core examination site (50). The contract content is not clearly stipulated
Chapter 3 business function development (delete clues)
Project management: lean management method