mysql行转列、列转行

建表语句

DROP TABLE IF EXISTS `ff`;
CREATE TABLE `ff` (
  `year` int(255) DEFAULT NULL,
  `month` int(255) DEFAULT NULL,
  `amount` float(255,1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `ff` VALUES ('1991', '1', '1.1');
INSERT INTO `ff` VALUES ('1991', '2', '1.2');
INSERT INTO `ff` VALUES ('1991', '3', '1.3');
INSERT INTO `ff` VALUES ('1991', '4', '1.4');
INSERT INTO `ff` VALUES ('1992', '1', '2.1');
INSERT INTO `ff` VALUES ('1992', '2', '2.2');
INSERT INTO `ff` VALUES ('1992', '3', '2.3');
INSERT INTO `ff` VALUES ('1992', '4', '2.4');

行转列

利用max函数实现行转列

mysql行转列、列转行_第1张图片

SELECT
    `year`,
    MAX(
        CASE `month`
        WHEN 1 THEN
            amount
        ELSE
            0
        END
    ) AS 'm1',
    MAX(
        CASE `month`
        WHEN 2 THEN
            amount
        ELSE
            0
        END
    ) AS 'm2',
    MAX(
        CASE `month`
        WHEN 3 THEN
            amount
        ELSE
            0
        END
    ) AS 'm3',
    MAX(
        CASE `month`
        WHEN 4 THEN
            amount
        ELSE
            0
        END
    ) AS 'm4'
FROM
    ff
GROUP BY
    `year` 

列转行

使用union 来实现列转行
这里我偷懒了,将行转列的结果作为视图,没有重新建表,效果是一样的。

mysql行转列、列转行_第2张图片

SELECT * FROM(SELECT
    `year`,
    1 AS 'month',
    `m1` AS amount
FROM
    ffe
UNION
    SELECT
        `year`,
        2 AS 'month',
        `m2` AS amount
    FROM
        ffe
    UNION
        SELECT
            `year`,
            3 AS 'month',
            `m3` AS amount
        FROM
            ffe
        UNION
            SELECT
                `year`,
                4 AS 'month',
                `m4` AS amount
            FROM
                ffe) AS wws
ORDER BY `year`,`month` ASC

你可能感兴趣的:(数据库)