• Oracle行转列实例


    行转列

    1.oracle的pivot函数

    原表

    使用pivot函数:

    with temp as(
    select '四川省' nation ,'成都市' city,'第一' ranking from dual union all
    select '四川省' nation ,'绵阳市' city,'第二' ranking from dual union all
    select '四川省' nation ,'德阳市' city,'第三' ranking from dual union all
    select '四川省' nation ,'宜宾市' city,'第四' ranking from dual union all
    select '湖北省' nation ,'武汉市' city,'第一' ranking from dual union all
    select '湖北省' nation ,'宜昌市' city,'第二' ranking from dual union all
    select '湖北省' nation ,'襄阳市' city,'第三' ranking from dual
    )
    select * from (select nation,city,ranking from temp)pivot (max(city) for ranking in ('第一' as 第一,'第二' AS 第二,'第三' AS 第三,'第四' AS 第四));

    说明:pivot(聚合函数 for 列名 in(类型)),其中 in(‘’) 中可以指定别名,in中还可以指定子查询,比如 select distinct ranking from temp

    复制代码
    SELECT * FROM [StudentScores] /*数据源*/
    AS P
    PIVOT 
    (
        SUM(Score/*行转列后 列的值*/) FOR 
        p.Subject/*需要行转列的列*/ IN ([语文],[数学],[英语],[生物]/*列的值*/)
    ) AS T
    复制代码

    列转行

    原表

    with temp as(
    select '四川省' nation ,'成都市' 第一,'绵阳市' 第二,'德阳市' 第三,'宜宾市' 第四  from dual union all
    select '湖北省' nation ,'武汉市' 第一,'宜昌市' 第二,'襄阳市' 第三,'' 第四   from dual
    )
    select nation,name,title from
    temp
    unpivot
    (name for title in (第一,第二,第三,第四))t

     说明:unpivot(自定义列名/*列的值*/ for 自定义列名/*列名*/ in(列名))

    参考:https://www.cnblogs.com/liudi1992/p/6039343.html

  • 相关阅读:
    STM32 --- 什么时候打开复用IO的时钟(比如RCC_APB2Periph_AFIO)
    STM32 一直进入串口接收中断
    printf 中的 %.*s
    形参定义为二级指针,可以修改实参指针本身的值
    结构体和联合体配合使用
    自定义注解的实现思路
    log4j application.properties 配置文件
    外观设计模式
    适配器设计模式
    模版方法设计模式
  • 原文地址:https://www.cnblogs.com/snailgirl/p/14768855.html
Copyright © 2020-2023  润新知