实际情况:工作中遇到这种表格,需要查询到每个key='key'(即费用编码)对应的key='value'(即减免金额)的值
因此就需要用到行列转换,方便查询
需要的查询结果如下
sql语句如下(两种方式):
(1)利用oracle中的decode函数
1 select t.index_id, 2 MAX(decode(t.key, 'key', t.value, null)) as fee_code, 3 MAX(decode(t.key, 'value', t.value, null)) as reduction_fee, 4 MAX(decode(t.key, 'devalue', t.value, null)) as overdue_payperiod 5 from LA_T_REDUCTION_REGULAR t 6 where t.contract_id = '20171205D0904J9C0_18' 7 group by t.index_id 8 order by t.index_id
(2)使用case-when-then-else
1 SELECT t.index_id, 2 MAX(CASE 3 WHEN t.key = 'key' THEN 4 t.value 5 ELSE 6 null 7 END) fee_code, 8 MAX(CASE 9 WHEN t.key = 'value' THEN 10 t.value 11 ELSE 12 null 13 END) reduction_fee, 14 MAX(CASE 15 WHEN t.key = 'devalue' THEN 16 t.value 17 ELSE 18 null 19 END) overdue_payperiod 20 FROM LA_T_REDUCTION_REGULAR t 21 where t.contract_id = '20171205D0904J9C0_18' 22 GROUP BY t.index_id 23 order by t.index_id
相比较而言,使用decode函数sql语句显得更为简洁,但二者实际的内部逻辑是相同的,而且decode函数是oracle特有的。