CASE expression is a very important and convenient technology in SQL. We should learn to use it to describe conditional branches.
This section will
introduce the use of CASE expressions through example questions such as row and column conversion, regrouping of existing data (classification), combined use with constraints, and conditional branching for aggregation results .
Quoted from "SQL Advanced Tutorial"
1. Data Sheet
CREATE TABLE `demo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `nameIndex` (`name`),
FULLTEXT KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 |
INSERT INTO `demo`.`demo`(`id`, `name`, `create_time`, `sex`) VALUES (1, 'zhangsan', '2020-06-01 23:23:52', '1');
INSERT INTO `demo`.`demo`(`id`, `name`, `create_time`, `sex`) VALUES (2, 'lisi', '2020-06-01 23:23:52', '0');
INSERT INTO `demo`.`demo`(`id`, `name`, `create_time`, `sex`) VALUES (3, 'wangwu', '2020-07-01 23:23:52', '0');
INSERT INTO `demo`.`demo`(`id`, `name`, `create_time`, `sex`) VALUES (4, 'zhaosi', '2020-05-01 23:23:52', '2');
INSERT INTO `demo`.`demo`(`id`, `name`, `create_time`, `sex`) VALUES (5, 'libai', '2020-07-08 13:33:38', '0');
INSERT INTO `demo`.`demo`(`id`, `name`, `create_time`, `sex`) VALUES (6, 'bajie', '2020-04-01 13:34:53', '1');
2. Demand
According to the user table below, count the number of users created in the last 2 months. Users created in other months will display "Other"
statistical results
Three, SQL statement
1. How to write CASE expression
Simple CASE expression
CASE sex
WHEN '1' THEN 'Male'
WHEN' 0 'THEN' Female'
ELSE 'Other' END
2. Write the following sql for the needs
SELECT CASE
WHEN DATE_FORMAT(create_time, '%Y-%m') = '2020-07' THEN '2020-07'
WHEN DATE_FORMAT(create_time, '%Y-%m') = '2020-06' THEN '2020-06'
ELSE '其他'
END AS month, COUNT(create_time) AS num
FROM demo
GROUP BY CASE
WHEN DATE_FORMAT(create_time, '%Y-%m') = '2020-07' THEN '2020-07'
WHEN DATE_FORMAT(create_time, '%Y-%m') = '2020-06' THEN '2020-06'
ELSE '其他'
END
ORDER BY create_time DESC
Note: If you have to display the month without data, you can use the code to solve it to keep the succinctness of the sql statement.