PL / SQL-基于列值创建动态查询块

时间:2015-02-28 18:16:05

标签: join plsql oracle11g dynamic-programming

表trans_data的列tran_type,其值为' V' M' M'' MC'' P'

目前使用多个联接:

(          
    select count(tran_type) Visa, to_char(request_datetime,'hh24') src_hour from trans_data where tran_type = 'V' group by to_char(request_datetime,'hh24')
  ) b on a.src_hour = b.src_hour left join

  (
    select count(tran_type) Maestro, to_char(request_datetime,'hh24') src_hour from trans_data where switched_type = 'M' group by to_char(request_datetime,'hh24')                   
  ) c on  a.src_hour = c.src_hour left join

上述块需要重复进行其他输入,例如' MC' - 万事达卡和' P'贝宝。将来,可能会有更多的交易类型。有没有办法,上面的代码可以根据tran_type的数量动态创建?

对于前。如果明天,我们包括' P' PayPal,动态查询应如下所示:

(          
    select count(tran_type) Visa, to_char(request_datetime,'hh24') src_hour from trans_data where tran_type = 'V' group by to_char(request_datetime,'hh24')
  ) b on a.src_hour = b.src_hour left join

  (
    select count(tran_type) Maestro, to_char(request_datetime,'hh24') src_hour from trans_data where tran_type = 'M' group by to_char(request_datetime,'hh24')                   
  ) c on  a.src_hour = c.src_hour left join

(
    select count(tran_type) PayPal, to_char(request_datetime,'hh24') src_hour from trans_data where tran_type = 'P' group by to_char(request_datetime,'hh24')                   
  ) d on  a.src_hour = d.src_hour left join

1 个答案:

答案 0 :(得分:0)

对于此类查询类型,您应该在select语句中使用PIVOT子句。请求的tran_type值列表可以在“for tran_type in”列表中动态更改。

select * from
(select to_char(request_datetime,'hh24') src_hour, tran_type from trans_data)
pivot
(
   count(tran_type)
   for tran_type in ('V' as "Visa",'M' as "Maestro",'P' as "PayPal")
)
order by src_hour