0

在 Oracle 11g 上使用 PL/SQL 如何编写查询以返回所需的结果?我想要使​​用许可证表的 expiry_date 的详细信息总和。每个 group by 中的所有事务必须在 expiry_date 之前发生。

Licenses

license_type vendor_code  funding_code  license_expiry_date 
---------------------------------------------------------------------------
CAB           1001        XR1           07/09/2011 4:23:18 pm
CAB           1002        XR2           07/06/2012 10:22:16 am

License_detail
register_period  license_type   active_date  fee  
---------------------------------------------------------------------
2012A            CAB             06/01/2011  25.00
2012A            CAB             07/01/2011  25.00
2012A            CAB             08/01/2011  30.00
2012A            CAB             09/01/2011  30.00
2012A            CAB             07/10/2012  40.00
2012A            CAB             07/11/2012  40.00

Desired Result

Period    Type   Funding   Vendor  TotalFees Expiry_Date
---------------------------------------------------------
2012A      CAB   XR1       1001     50.00    07/09/2011 4:23:18 pm
2012A      CAB   XR2       1002     60.00    07/06/2012 10:22:16 am
2012A      CAB   <null>    <null>   80.00    <null>        
4

1 回答 1

3

您需要的是许可证的生效日期和结束日期。然后,您可以将其加入许可证详细信息,如下所示:

select ld.period, ld.type, l.funding_code, l.vendor_code, sum(fee) as fee,
       l.license_expiry_date
from license_detail ld left outer join
     (select l.*,
             lead(license_expiry_date, 1) over (partition by license_type
                                                order by license_expiry_date)
                                               ) as nextdate
      from licenses l
     ) l
     on ld.license_type = l.license_type and
        ld.active_date >= coalesce(license_expiry_date, ld.active_date) and
        ld.active_date < coalesce(nextdate, to_date('9999-01-01', 'yyyy-mm-dd'))
group by ld.period, ld.type, l.funding_code, l.vendor_code, l.license_expiry_date
于 2012-08-28T02:48:40.343 回答