如何用SQL語(yǔ)句在MySQL中進(jìn)行數(shù)據(jù)透視

小樊
85
2024-09-12 02:41:09
欄目: 云計(jì)算

在 MySQL 中,可以使用 CASE 語(yǔ)句實(shí)現(xiàn)數(shù)據(jù)透視

首先,創(chuàng)建一個(gè)示例表格并插入數(shù)據(jù):

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);

接下來(lái),使用 SQL 語(yǔ)句和 CASE 語(yǔ)句進(jìn)行數(shù)據(jù)透視:

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;

這將返回以下結(jié)果:

+------------+--------------+----------------+
| product_id | January_sales| February_sales |
+------------+--------------+----------------+
|          1 |          100|             200 |
|          2 |          150|             250 |
+------------+--------------+----------------+

在此示例中,我們使用了 CASE 語(yǔ)句對(duì)每個(gè)月的銷售額進(jìn)行條件求和。通過(guò)對(duì) product_id 進(jìn)行分組,我們可以得到每個(gè)產(chǎn)品在每個(gè)月的銷售額。

0