CASE 语法
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
将表中的内容转换为右边的形式:
1、创建表,创建数据
CREATE TABLEchapter10_7 (
order_id VARCHAR(255) NULL,
price VARCHAR(255) NULL,
deal_date VARCHAR(255) NULL,
area VARCHAR(255) NULL
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_0900_ai_ci;
INSERT INTOchapter10_7 (order_id, price, deal_date, area) VALUES('S001', '10', '2019/1/1', 'A区');
INSERT INTOchapter10_7 (order_id, price, deal_date, area) VALUES('S002', '20', '2019/1/1', 'B区');
INSERT INTOchapter10_7 (order_id, price, deal_date, area) VALUES('S003', '30', '2019/1/1', 'C区');
INSERT INTOchapter10_7 (order_id, price, deal_date, area) VALUES('S004', '40', '2019/1/2', 'A区');
INSERT INTOchapter10_7 (order_id, price, deal_date, area) VALUES('S005', '10', '2019/1/2', 'B区');
INSERT INTOchapter10_7 (order_id, price, deal_date, area) VALUES('S006', '20', '2019/1/2', 'C区');
INSERT INTOchapter10_7 (order_id, price, deal_date, area) VALUES('S007', '30', '2019/1/3', 'A区');
INSERT INTOchapter10_7 (order_id, price, deal_date, area) VALUES('S008', '40', '2019/1/3', 'C区');
2、SQL解决:
-- 选择 deal_date 和三个区域的订单数量
SELECT
a.deal_date, -- 选择 deal_date 列
COUNT(CASE WHEN a.area = 'A区' THEN order_id ELSE NULL END) AS A区, -- 计算 A区的订单数量
COUNT(CASE WHEN a.area = 'B区' THEN order_id ELSE NULL END) AS B区, -- 计算 B区的订单数量
COUNT(CASE WHEN a.area = 'C区' THEN order_id ELSE NULL END) AS C区 -- 计算 C区的订单数量
FROM
chapter10_7 a -- 从 chapter10_7 表中选择数据,并给这个表起了一个别名 'a'
GROUP BY
a.deal_date; -- 根据 deal_date 进行分组,这样我们可以为每个 deal_date 计算三个区域的订单数量
CASE when 实战练习拓展:
SELECT
order_id,
price,
CASE
WHEN price <= 10 THEN '价格低'
WHEN price >= 10 AND price <= 20 THEN '价格中等'
WHEN price >= 30 THEN'价格高等'
ELSE '价格有问题'
END AS price_category
FROM
demo.chapter10_7