• oracle行转列、列转行总结


    1.行转列

    (1)decode实现

    SELECT t_year,
    MAX(DECODE(t_month,‘1月’,t_value)) AS 一月,
    MAX(DECODE(t_month,‘2月’,t_value)) AS 二月,
    MAX(DECODE(t_month,‘3月’,t_value)) AS 三月,
    MAX(DECODE(t_month,‘4月’,t_value)) AS 四月
    FROM a_testtable WHERE t_month IN(‘1月’,‘2月’,‘3月’,‘4月’)
    GROUP BY t_year;

    (2)case when实现

    SELECT t_year,
    MAX(CASE t_month WHEN ‘1月’ THEN t_value END) AS 一月,
    MAX(CASE t_month WHEN ‘2月’ THEN t_value END) AS 二月,
    MAX(CASE t_month WHEN ‘3月’ THEN t_value END) AS 三月,
    MAX(CASE t_month WHEN ‘4月’ THEN t_value END) AS 四月
    FROM a_testtable WHERE t_month IN(‘1月’,‘2月’,‘3月’,‘4月’)
    GROUP BY t_year;

    (3)pivot函数

    SELECT * FROM a_testtable
    PIVOT(SUM(t_value) FOR t_month IN(‘1月’ AS 一月,‘2月’ AS 二月,‘3月’ AS 三月,‘4月’ AS 四月));

    SELECT * FROM
    (SELECT t_year AS ye,t_month AS mon,t_value AS val FROM a_testtable) a
    PIVOT(SUM(val) FOR mon IN(‘1月’ AS 一月,‘2月’ AS 二月,‘3月’ AS 三月,‘4月’ AS 四月));

    2列转行

    准备表及数据

    (1)decode实现

    SELECT t_year,
    DECODE(lvl,1,‘1月’,2,‘2月’,3,‘3月’,4,‘4月’) AS t_month,
    DECODE(lvl,1,one_m,2,two_m,3,tree_m,4,four_m) AS t_qty
    FROM b_testtable,(SELECT LEVEL lvl FROM dual CONNECT BY LEVEL<=4)
    ORDER BY t_year,t_month;

    (2)case when实现

    SELECT t_year,
    CASE lvl WHEN 1 THEN ‘1月’
    WHEN 2 THEN ‘2月’
    WHEN 3 THEN ‘3月’
    WHEN 4 THEN ‘4月’
    END AS t_month,
    CASE lvl WHEN 1 THEN one_m
    WHEN 2 THEN two_m
    WHEN 3 THEN tree_m
    WHEN 4 THEN four_m
    END AS t_qty
    FROM b_testtable,(SELECT LEVEL lvl FROM dual CONNECT BY LEVEL<=4)
    ORDER BY t_year,t_month;

    (3)unpivot函数实现

    SELECT * FROM b_testtable
    UNPIVOT(t_qty FOR t_month IN(one_m AS ‘1月’,two_m AS ‘2月’,tree_m AS ‘3月’,four_m AS ‘4月’))
    ORDER BY t_year,t_month;

  • 相关阅读:
    语法练习:makes10
    高级架构师_Elasticsearch_第四章_企业级高可用分布式集群
    MKS上游和下游集成式压力控制器的技术分析及其替代解决方案
    CCIE重认证-300-410(选修)
    Abnova丨 CD81单克隆抗体相关参数和应用
    Springcloud之OAuth2
    MySQL数据库期末考试试题及参考答案(04)
    MFC的CPen与CBush画图对象使用步骤
    栈的基本操作以及C语言实现
    计算机Java项目|基于SpringBoot的网上摄影工作室
  • 原文地址:https://blog.csdn.net/m0_67403240/article/details/126038821