zoukankan      html  css  js  c++  java
  • oracle 列转行

    工作需求:

    查询出2017-01-01至2017-12-12时间段内  医疗机构为同济大学附属肺科医院  年龄段在40-55岁人群 的各项费用类型的平均值

    select 
    ROUND(AVG(M1.YPFY), 2) as 药品费用,
    ROUND(AVG(M1.JCFY), 2) as 检查费用,
    ROUND(AVG(m1.JYFY), 2) as 检验费用,
    ROUND(AVG(M1.SSFY), 2) as 手术费用,
    ROUND(AVG(M1.ZLFY), 2) as 治疗费用,
    ROUND(AVG(M1.QTFY), 2) as 其他费用  
    from CB_ME_YLFY m1,
    (select a.SJID ,a.YLJGID,a.FBNLID,a.JZLXID 
    from 
    CB_ME_FBNL a,
    (SELECT FBNLID FROM CB_DI_FBNL) b,
    (select SJID from (select SJID, SUBSTR(SJMC,1,4) || '-' || SUBSTR(SJMC,5,6) || '-01' as t from CB_DI_DATE) dat where dat.t >= '2017-01-01' AND dat.t < '2017-12-12') c,
    (select YLJGID from CB_DI_YLJG) d ,
    (select JZLXID,JZLXMC from CB_DI_JZLX ) e 
    where 
    a.SJID = c.SJID AND a.FBNLID = b.FBNLID 
    AND a.YLJGID = d.YLJGID AND a.JZLXID = e.JZLXID) m2 
    WHERE M1.SJID = M2.SJID AND M1.YLJGID = M2.YLJGID AND M1.JZLXID = M2.JZLXID

    查询结果:

    我要将行转为列变成下面的样式:

     type      count

    药品费用    4058.63

    检查费用                502.81

    实现:

    with ttt as (select ROUND(AVG(M1.YPFY), 2) as 药品费用,ROUND(AVG(M1.JCFY), 2) as 检查费用,ROUND(AVG(m1.JYFY), 2) as 检验费用,
    ROUND(AVG(M1.SSFY), 2) as 手术费用,
    ROUND(AVG(M1.ZLFY), 2) as 治疗费用,
    ROUND(AVG(M1.QTFY), 2) as 其他费用  
    from CB_ME_YLFY m1,
    (select a.SJID ,a.YLJGID,a.FBNLID,a.JZLXID from CB_ME_FBNL a,(SELECT FBNLID FROM CB_DI_FBNL) b,
    (select SJID from (select SJID, SUBSTR(SJMC,1,4) || '-' || SUBSTR(SJMC,5,6) || '-01' as t from CB_DI_DATE) dat 
    where dat.t >= '2017-01-01' AND dat.t < '2017-12-12') c,(select YLJGID from CB_DI_YLJG) d ,
    (select JZLXID,JZLXMC from CB_DI_JZLX ) e 
    where a.SJID = c.SJID AND a.FBNLID = b.FBNLID 
    AND a.YLJGID = d.YLJGID AND a.JZLXID = e.JZLXID) m2 
    WHERE M1.SJID = M2.SJID AND M1.YLJGID = M2.YLJGID AND M1.JZLXID = M2.JZLXID)
    
    select 费用类型 as type, 金额 as count 
    from ttt
    unpivot (金额 for 费用类型 in (药品费用, 检查费用, 检验费用, 手术费用,治疗费用,其他费用) )

    结果:

     

    前进时,请别遗忘了身后的脚印。
  • 相关阅读:
    Mysql锁机制--读锁
    分布式自增ID算法snowflake
    MySql的时区(serverTimezone)引发的血案
    springBoot2.x启动项目报java.sql.SQLNonTransientConnectionException
    idea生成构造方法的快捷键(看这篇就够了)
    MYSQLl给用户授予数据库表权限
    SpringBoot2.x打包成war(看这篇就够了)
    linux下tar命令解压到指定的目录
    MySQL的JDBC驱动(8.0版本)
    使用TortoiseGit(乌龟)上传本地项目至码云
  • 原文地址:https://www.cnblogs.com/liudaihuablogs/p/9149362.html
Copyright © 2011-2022 走看看