当前位置:网站首页>[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;
边栏推荐
猜你喜欢

26 points that must be paid attention to for stability test

文件操作(一)——文件简介与文件的打开方式和关闭
![[translation] safety. Value of sboms](/img/8b/1ad825e7c9b6a87ca1fea812556f3a.jpg)
[translation] safety. Value of sboms

这种动态规划你见过吗——状态机动态规划之股票问题(上)

案例:使用keepalived+Haproxy搭建Web群集

Shardingsphere data slicing

Vofa+ serial port debugging assistant
![[纯理论] YOLO v4: Optimal Speed and Accuracy of Object Detection](/img/1f/f38c3b38feed9e831ad84b4bbf81c0.png)
[纯理论] YOLO v4: Optimal Speed and Accuracy of Object Detection

Binary search 33. search rotation sort array

Cycle and branch (I)
随机推荐
循环与分支(一)
MySQL tutorial: MySQL database learning classic (from getting started to mastering)
VOFA+ 串口调试助手
JS get the time composition array of two time periods
Autojs cloud control source code + display
How to effectively prevent others from wearing the homepage snapshot of the website
Usage of arguments.callee
Pipnet: face key point detection for natural scenes "pixel in pixel net: directions efficient facial landmark detection in the wild"
Self-supervised learning method to solve the inverse problem of Fokker-Planck Equation
基础知识-网络与服务器
如何有效的去防止别人穿该网站首页快照
[steering wheel] use the 60 + shortcut keys of idea to share with you, in order to improve efficiency (reconstruction)
ES6高级-利用构造函数继承父类属性
MySQL建Websites数据表
(9) Attribute introspection
Qt 信号在多层次对象间传递 多层嵌套类对象之间信号传递
测试/开发程序员老了怎么办?挥之不去残酷的事实......
HLS实验一--乘法器
How about GF Securities? Is it safe to open an account online?
eslint常见报错集合