Oracle SQL子查询如何使用查询A的结果来限制查询B.

时间:2012-02-03 21:51:45

标签: sql oracle subquery

目标:

  • 合并我目前运行的两个查询。
  • 让查询1的WEEK成为查询2的过滤条件。

查询1:

----------------------------------------------------
-- ************************************************
-- Accounts Recieveable (WEEKLY) snapshot
-- ************************************************
----------------------------------------------------
SELECT 
    TRUNC(TX.ORIG_POST_DATE,'WW') AS WEEK, 
    SUM(TX.AMOUNT) AS OUTSTANDING
FROM 
    TX
WHERE
    --Transaction types
    (TX.DETAIL_TYPE = "Charges" OR 
    TX.DETAIL_TYPE = "Payments" OR 
    TX.DETAIL_TYPE = "Adjustments") 
GROUP BY
    TRUNC(tx.ORIG_POST_DATE,'WW')
ORDER BY
    TRUNC(tx.ORIG_POST_DATE,'WW')

输出查询1:

    WEEK    OUTSTANDING
1/1/2012    18203.95
1/8/2012    17605
1/15/2012   19402.33
1/22/2012   18693.45
1/29/2012   19100

查询2:

----------------------------------------------------
-- ************************************************
-- Weekly Charge AVG over previous 13 weeks based on WEEK above
-- ************************************************
----------------------------------------------------

SELECT 
    sum(tx.AMOUNT)/91
FROM 
    TX
WHERE
    --Post date
    TX.ORIG_POST_DATE <= WEEK AND
    TX.ORIG_POST_DATE >= WEEK-91 AND
    --Charges
    (TX.DETAIL_TYPE = "Charge")

输出查询2:

thirteen_Week_Avg
1890.15626

所需输出

WEEK        OUTSTANDING Thirteen_Week_Avg
1/1/2012    18203.95    1890.15626
1/8/2012    17605       1900.15626
1/15/2012   19402.33    1888.65132
1/22/2012   18693.45    1905.654
1/29/2012   19100       1900.564

注意Thirteen_Week_Avg是“WEEK”字段前13周。因此,随着平均窗口向前移动,它每周都会发生变化。

另外你们知道哪些教程我能阅读以更好地理解这类问题的解决方案?

2 个答案:

答案 0 :(得分:4)

尝试使用分析函数,例如:

  select WEEK, sum(OUTSTANDING) as OUTSTANDING, THIRTEEN_WEEK_AVG
    from (select trunc(TX.ORIG_POST_DATE, 'WW') as WEEK
                ,AMOUNT as OUTSTANDING
                ,avg(
                   TX.AMOUNT)
                 over (order by trunc(TX.ORIG_POST_DATE, 'WW')
                       range numtodsinterval(7 * 13, 'day') preceding)
                   as THIRTEEN_WEEK_AVG
            from TX
           where (TX.DETAIL_TYPE = 'Charges'
                  or TX.DETAIL_TYPE = 'Payments'
                  or TX.DETAIL_TYPE = 'Adjustments'))
group by WEEK, THIRTEEN_WEEK_AVG
order by WEEK

可以找到分析函数的介绍hereNUMTODSINTERVAL的工作原理是here

答案 1 :(得分:1)

我首先想到的是,这最好由一个存储过程来处理,该存储过程设置两个游标,每个游标一个,每个游标都有一个周参数。您可以调用第一个输出周和未完成的光标,然后多次循环,并每次返回1周。然后将那一周传递给十三周的平均光标并让它输出平均值。

如果您只是想在屏幕上显示它,可以使用dbms_output.put_line。如果要将其写入文件(如csv),则需要设置文件处理程序和所有相关的管道以创建/打开/写入/保存文件。

O'reilly有一本非常好的pl / sql书,可以很好地解释过程和游标。