亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

如何使用存儲過程在MySQL中實現數據透視

小樊
83
2024-09-12 02:50:54
欄目: 云計算

在MySQL中,您可以使用存儲過程來實現數據透視

  1. 首先,創建一個包含數據的示例表:
CREATE TABLE sales_data (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(255),
    month VARCHAR(255),
    sales INT
);

INSERT INTO sales_data (product_name, month, sales)
VALUES ('Product A', 'January', 100),
       ('Product A', 'February', 200),
       ('Product B', 'January', 150),
       ('Product B', 'February', 250);
  1. 創建一個存儲過程來實現數據透視:
DELIMITER //
CREATE PROCEDURE pivot_sales_data()
BEGIN
    -- Declare variables
    DECLARE done INT DEFAULT 0;
    DECLARE cur CURSOR FOR SELECT DISTINCT month FROM sales_data;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
    DECLARE @query VARCHAR(4096);
    DECLARE @month VARCHAR(255);

    -- Create a temporary table to store pivoted data
    DROP TEMPORARY TABLE IF EXISTS temp_pivot;
    CREATE TEMPORARY TABLE temp_pivot (
        product_name VARCHAR(255)
    );

    -- Open the cursor and loop through each month
    OPEN cur;
    read_loop: LOOP
        FETCH cur INTO @month;
        IF done THEN
            LEAVE read_loop;
        END IF;

        -- Add a new column for each month in the temporary table
        SET @query = CONCAT('ALTER TABLE temp_pivot ADD COLUMN `', @month, '` INT');
        PREPARE stmt FROM @query;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END LOOP;
    CLOSE cur;

    -- Populate the temporary table with pivoted data
    SET @query = '
        INSERT INTO temp_pivot (product_name, January, February)
        SELECT product_name,
               SUM(CASE WHEN month = ''January'' THEN sales ELSE 0 END) AS January,
               SUM(CASE WHEN month = ''February'' THEN sales ELSE 0 END) AS February
        FROM sales_data
        GROUP BY product_name';
    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    -- Select the pivoted data from the temporary table
    SELECT * FROM temp_pivot;
END//
DELIMITER ;
  1. 調用存儲過程以查看透視后的數據:
CALL pivot_sales_data();

這將返回以下結果:

+-------------+---------+----------+
| product_name | January | February |
+-------------+---------+----------+
| Product A   |     100 |      200 |
| Product B   |     150 |      250 |
+-------------+---------+----------+

請注意,此示例僅適用于具有固定月份列的簡單數據透視。對于更復雜的數據透視需求,您可能需要根據您的具體情況修改存儲過程。

0
鄄城县| 淅川县| 应用必备| 五莲县| 西青区| 福贡县| 施甸县| 呼玛县| 平顺县| 马公市| 宜州市| 太仓市| 深圳市| 峨边| 宝应县| 马公市| 元氏县| 高青县| 梓潼县| 新竹市| 新闻| 公主岭市| 汝南县| 临澧县| 马尔康县| 红桥区| 建宁县| 龙游县| 新巴尔虎左旗| 南丰县| 东丽区| 临夏县| 韶山市| 沅陵县| 呼和浩特市| 左权县| 花莲县| 闽清县| 达州市| 朝阳县| 武鸣县|