91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

如何使用存儲過程在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
茂名市| 平果县| 文化| 泸定县| 资讯| 瑞昌市| 东宁县| 怀集县| 涿州市| 始兴县| 稻城县| 三江| 碌曲县| 江陵县| 榆林市| 吉木乃县| 永城市| 清丰县| 徐州市| 连平县| 甘谷县| 黄梅县| 临沭县| 绥滨县| 石阡县| 台中县| 太白县| 乐清市| 建宁县| 聂荣县| 仙游县| 沾益县| 日照市| 建阳市| 留坝县| 新乐市| 四川省| 满城县| 富裕县| 宜丰县| 嵩明县|