阅读量:0
在 MySQL 中,可以使用 CASE 语句实现数据透视
首先,创建一个示例表格并插入数据:
CREATE TABLE sales_data ( product_id INT, month VARCHAR(10), sales INT ); INSERT INTO sales_data (product_id, month, sales) VALUES (1, 'January', 100), (1, 'February', 200), (2, 'January', 150), (2, 'February', 250);
接下来,使用 SQL 语句和 CASE 语句进行数据透视:
SELECT product_id, SUM(CASE WHEN month = 'January' THEN sales ELSE 0 END) AS January_sales, SUM(CASE WHEN month = 'February' THEN sales ELSE 0 END) AS February_sales FROM sales_data GROUP BY product_id;
这将返回以下结果:
+------------+--------------+----------------+ | product_id | January_sales| February_sales | +------------+--------------+----------------+ | 1 | 100| 200 | | 2 | 150| 250 | +------------+--------------+----------------+
在此示例中,我们使用了 CASE 语句对每个月的销售额进行条件求和。通过对 product_id 进行分组,我们可以得到每个产品在每个月的销售额。