001-Oracle行转列

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、正数还是负数,分别返回01-1
变量1=10,变量2=20
则sign(变量1-变量2)返回-1**decode**解码结果为“变量1”,达到了取较小值的目的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值