有一个sales的表,它记录了不同产品在不同月份的销售情况:
product | January | February | March |
---|---|---|---|
Product A | January | 10 | |
Product A | February | 20 | |
Product B | January | 5 | |
Product B | February | 15 | |
Product C | January | 8 | |
Product C | February | 12 |
客户需求展示为如下的样子:
product | January | February | March |
---|---|---|---|
Product A | 10 | 20 | 0 |
Product B | 5 | 15 | 0 |
Product C | 8 | 12 | 0 |
#行转列概念
行转列操作指的是将表格中一行数据转换为多列数据的操作。
SQL解决:
--创建表
CREATE TABLE sales (
id INT AUTO_INCREMENT PRIMARY KEY,
product VARCHAR(255),
month VARCHAR(255),
quantity INT
);
--插入数据
INSERT INTO sales (product, month, quantity) VALUES
('Product A', 'January', 10),
('Product A', 'February', 20),
('Product B', 'January', 5),
('Product B', 'February', 15),
('Product C', 'January', 8),
('Product C', 'February', 12);
–查询语句
SELECT
product,
MAX(CASE WHEN month = 'January' THEN quantity ELSE 0 END) AS January,
MAX(CASE WHEN month = 'February' THEN quantity ELSE 0 END) AS February,
MAX(CASE WHEN month = 'March' THEN quantity ELSE 0 END) AS March
FROM
sales
GROUP BY
product;
查询语句的解释如下:
MAX(CASE WHEN … THEN … ELSE … END): 这是一个条件聚合函数,它检查month字段的值,并在条件为真时返回相应的quantity值,否则返回0。MAX函数在这里用于确保即使有多个月份相同的记录,也只返回一个值。
AS January, AS February, AS March: 这些是列的别名,将结果列重命名为对应的月份。
FROM sales: 指定查询的表名为sales。
GROUP BY product: 按照product字段对结果进行分组,这样每个产品的销售情况都会在一行中显示。
执行上述查询后,你会得到如下结果:
product | January | February | March |
---|---|---|---|
Product A | 10 | 20 | 0 |
Product B | 5 | 15 | 0 |
Product C | 8 | 12 | 0 |