Oracle行转列
需求:
需要获取8月和9月调用接口次数
名称 | 8月 | 9月 | 合计 |
---|---|---|---|
实现方案1:
select
trx_type as "名称",
AUG as "8月",
SEPT as "9月",
SUMS as "合计"
from (
select
trx_type,
to_char(create_ts,'mm') as month,
count(1) as c
from sys_log where msg_type = '响应报文'
group by trx_type, to_char(create_ts,'mm')
union all
select
trx_type,
'合计' as month,
count(trx_type) as c
from sys_log
where create_ts > to_date('2019-08-01','yyyy-mm-dd')
and create_ts < to_date('2019-10-01','yyyy-mm-dd')
and msg_type = '响应报文' group by trx_type
)
pivot (
sum(c) for month in
('08' as AUG, '09' AS SEPT, '合计' AS SUMS)
);
说明: pivot(聚合函数 for 列名 in(类型))
--其中 in('') 中可以指定别名,in中还可以指定子查询,比如 select distinct ranking from temp
实现方案2:
SELECT
DECODE(GROUPING(T.type1), 1, '接口调用总计', T.type1) as "名称",
SUM(DECODE(T.month1, '8月', T.num1, 0)) as "8月",
SUM(DECODE(T.month1, '9月', T.num1, 0)) as "9月",
SUM(T.num1) as "合计"
FROM
(
select
trx_type as type1,
count(trx_type) as num1,
'8月' as month1
from sys_log
where create_ts >= to_date('2019-08-01','yyyy-mm-dd')
and create_ts < to_date('2019-09-01','yyyy-mm-dd')
and msg_type = '响应报文' group by trx_type
union all
select
trx_type as type1,
count(trx_type) as num1,
'9月' as month1
from sys_log
where create_ts >= to_date('2019-09-01','yyyy-mm-dd')
and create_ts < to_date('2019-10-01','yyyy-mm-dd')
and msg_type = '响应报文' group by trx_type
) T
GROUP BY ROLLUP(T.type1);
decode(条件,值1,返回值1,值2,返回值2,…值n,返回值n,缺省值)
该函数的含义如下:
IF 条件=值1 THEN
RETURN(翻译值1)
ELSIF 条件=值2 THEN
RETURN(翻译值2)
…
ELSIF 条件=值n THEN
RETURN(翻译值n)
ELSE
RETURN(缺省值)
END IF
示例:
SELECT ID,DECODE(inParam,'para1','值1' ,'para2','值2','para3','值3','para4','值4','para5','值5') name FROM bank
#如果第一个参数inParam=='para1'那么那么select得到的那么显示为值1;
#如果第一个参数inParam=='para2'那么那么select得到的那么显示为值2;
#如果第一个参数inParam=='para3'那么那么select得到的那么显示为值3;
#如果第一个参数inParam=='para4'那么那么select得到的那么显示为值4;
#如果第一个参数inParam=='para5'那么那么select得到的那么显示为值5;
#都不相等就为''
decode(字段或字段的运算,值1,值2,值3)
这个函数运行的结果是,当字段或字段的运算的值等于值1时,该函数返回值2,否则返回值3
当然值1,值2,值3也可以是表达式,这个函数使得某些sql语句简单了许多
示例:
SELECT ID,DECODE(inParam,'beComparedParam','值1' ,'值2') name FROM bank
#如果第一个参数inParam=='beComparedParam',则select得到的name显示为值1,
#如果第一个参数inParam!='beComparedParam',则select得到的name显示为值2
select decode(sign(变量1-变量2), -1, 变量1. 变量2) from dual; --取较小值
sign()函数根据某个值是0、正数还是负数,分别返回0、1、-1
变量1=10,变量2=20
则sign(变量1-变量2)返回-1,**decode**解码结果为“变量1”,达到了取较小值的目的。