使用此SQL样式有什么好处?

时间:2015-09-03 01:30:04

标签: sql oracle

我有以下SQL查询,其结构对我来说很奇怪:

SELECT 
  SUM("x1") AS "X1 col",
  SUM("x2") AS "X2 col"
FROM (
  SELECT DISTINCT xyz
  FROM some_tables
  WHERE some_cond
 );

实际代码在这里:

select 
  sum("Req Lines") as "Requisitions Created",
  sum("Approved Req") as "Requisitions Approved",
  sum("Non Approved PO") as "PO Started",
  sum("Approved PO") as "PO Approved",
  sum("w/ Receipt") as "Receipts Completed",
  sum("w/ Invoice") as "Invoices Completed"
from(
  select distinct prha.Segment1 as "Req#", 
    pha.Segment1 as "PO#",
    CASE when prha.creation_date between to_date(:myDate,'DD-MON-YY') and to_date(:myDate,'DD-MON-YY') + 7  then 'Week 1' 
        when prha.creation_date between to_date(:myDate,'DD-MON-YY') + 7 and to_date(:myDate,'DD-MON-YY') + 14  then 'Week 2' 
        when prha.creation_date between to_date(:myDate,'DD-MON-YY') + 14 and to_date(:myDate,'DD-MON-YY') + 21 then 'Week 3'
        when prha.creation_date between to_date(:myDate,'DD-MON-YY') + 21 and to_date(:myDate,'DD-MON-YY') + 28  then 'Week 4' 
     else 'After Month 1' END as "Req_Created",
    --CASE when prha.creation_date < '28-Aug-2015' then 'Week 1' else 'After Week 1' END,
    1  as "Req Lines",
    prha.authorization_status as "Req Status",
    CASE when prha.authorization_status='APPROVED' then 1 else 0 END as "Approved Req",
    CASE when pha.authorization_status='APPROVED' then 1 else 0 END as "Approved PO",
    pha.authorization_status,
    CASE when (pha.authorization_status = 'APPROVED' or pha.authorization_status is null) then 0 else 1 END as "Non Approved PO",
    CASE when pda.quantity_delivered >=1 then 1 else 0 END as "w/ Receipt",
    CASE when pda.quantity_billed >=1 then 1 else 0 END as "w/ Invoice",
    prha.*, 
    prl.*
  from po_requisition_lines_all prl, 
    po_requisition_headers_all prha, 
    po_req_distributions_all prda, 
    po_distributions_all pda, 
    po_headers_all pha
  WHERE 1=1 
   AND prl.requisition_header_id = prha.requisition_header_id
  and prl.requisition_line_id = prda.requisition_line_id
  AND prda.distribution_id= pda.req_distribution_id(+)
  and pha.po_header_id(+) = pda.po_header_id
  --and item_description =  'Brads Test'
  and prda.creation_date > to_date(:myDate,'DD-MON-YY')
  and prha.org_id in (279,282,351,105,102) -- NA operating Units
)
;

我很好奇这个SQL是如何工作的,为什么你会使用这种SQL代码?

1 个答案:

答案 0 :(得分:2)

您所展示的只是从子查询中选择聚合。

您可以查询子查询的结果,这正是您的示例中正在执行的操作。从您所显示的内容来看,以这种方式编写查询并非100%的必要,但以这种方式编写查询也没有错。我可以想到其他方法可以获得相同的结果,但在SQL方面总是不止一种方法可以让猫皮肤。