2015-09-03 32 views
1

我有以下SQL查询,其结构看起来很奇怪对我说:使用这种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代码吗?

回答

2

你所显示的只是从子查询中选择聚合。

您可以查询子查询的结果,而这正是您的示例中所做的。从你所展示的内容来看,以这种方式编写查询不是100%必要的,但这样写就没有错。我可以想到其他方式可以得到相同的结果,但是在谈到SQL时总会有不止一种方法来剥皮猫。

+0

Nitpicking:显示的示例不是子查询,它是派生表 –

相关问题