有能耗表,记录各个城市水、电、热的能耗情况,表结构如下:
名称类型备注E_CODEVARCHAR2(10)城市的CODEE_VALUENUMBER能耗值,包括水耗、电耗、热耗E_TIMEVARCHAR2(20)时间E_TYPENUMBER能耗类型,0:水耗,1:电耗,2:热耗
插入测试数据,如下:
E_CODEE_VALUEE_TIMEE_TYPEBJ20.052018-08-29 01:00:000BJ36.352018-08-29 01:00:001BJ45.2232018-08-29 01:00:002SH22.952018-08-29 01:00:000SH18.45562018-08-29 01:00:001SH33.2542018-08-29 01:00:002GZ48.5542018-08-29 01:00:000GZ21.1122018-08-29 01:00:001GZ25.6252018-08-29 01:00:002
上面的表格是一张竖表,而我们想得到的是横表,即行转列,获得如下结果
编号时间水耗电耗热耗SH2018-08-29 01:00:0022.9518.455633.254GZ2018-08-29 01:00:0048.55421.11225.625BJ2018-08-29 01:00:0020.0536.3545.223
实现竖表转横表的查询,即行转列,通常有两种常用方法。
E_CODE,
E_TIME,
SUM( DECODE(E_TYPE, 0, E_VALUE) ) AS WATER_ENERGY,–水耗
SUM( DECODE(E_TYPE, 1, E_VALUE) ) AS ELE_ENERGY,–电耗
SUM( DECODE(E_TYPE, 2, E_VALUE) ) AS HEAT_ENERGY–热耗
FROM
THTF_ENERGY_TEST
GROUP BY
E_CODE,E_TIME
输出如下:
E_CODEE_TIMEWATER_ENERGYELE_ENERGYHEAT_ENERGYSH2018-08-29 00:00:0022.9518.445633.2540GZ2018-08-29 00:00:0048.554021.112025.6250BJ2018-08-29 00:00:0020.0536.3545.2230
简单case when函数:
E_CODE,
E_TIME,
SUM( CASE E_TYPE WHEN 0 THEN E_VALUE ELSE 0 END ) AS WATER_ENERGY,–水耗
SUM( CASE E_TYPE WHEN 1 THEN E_VALUE ELSE 0 END ) AS ELE_ENERGY,–电耗
SUM( CASE E_TYPE WHEN 2 THEN E_VALUE ELSE 0 END ) AS HEAT_ENERGGY–热耗
FROM
THTF_ENERGY_TEST
GROUP BY
E_CODE,E_TIME
输出结果同上:
E_CODEE_TIMEWATER_ENERGYELE_ENERGYHEAT_ENERGYSH2018-08-29 00:00:0022.9518.445633.2540GZ2018-08-29 00:00:0048.554021.112025.6250BJ2018-08-29 00:00:0020.0536.3545.2230
CASE WHEN函数功能很强大、实用,使用起来也简单易懂。在此篇文章详细介绍:CASE WHEN 用法详解
到此这篇关于Oracle实现竖表转横表的几种常用方法小结的文章就介绍到这了,更多相关Oracle 竖表转横表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!