根据您提供的信息,以下查询应生成您想要的结果。
SELECT TO_CHAR(month, 'MON-YYYY'),
DECODE(SIGN(planned_amount-(total_planned_amount-total_actual_amount)),
-1, planned_amount,
total_planned_amount-total_actual_amount) result
FROM (
SELECT month,
SUM(planned_amount) OVER (PARTITION BY month ORDER BY month) planned_amount,
SUM(planned_amount) OVER (ORDER BY month) total_planned_amount,
total_actual_amount
FROM (SELECT month,
planned_amount,
total_actual_amount
FROM (SELECT TRUNC(month, 'MM') month,
SUM(amount) planned_amount
FROM planned
GROUP BY TRUNC(month, 'MM')
),
(SELECT NVL(SUM(amount), 0) total_actual_amount
FROM actual
)
)
)
WHERE total_planned_amount - total_actual_amount > 0
ORDER BY month
内部查询使用笛卡尔连接来创建每个月的列表,以及该月的计划金额和所有发票的总和。
Month planned_amount total_actual_amount
Jan-2013 10000 35000
Feb-2013 10000 35000
Mar-2013 10000 35000
Apr-2013 10000 35000
May-2013 10000 35000
Jun-2013 10000 35000
然后它执行另一个查询来计算计划金额的运行总计。
Month planned_amount total_planned_amount total_actual_amount
Jan-2013 10000 10000 35000
Feb-2013 10000 20000 35000
Mar-2013 10000 30000 35000
Apr-2013 10000 40000 35000
May-2013 10000 50000 35000
Jun-2013 10000 60000 35000
然后,它将结果限制为仅那些total_planned_amount大于total_actual_amount的结果,并且对于每个月,返回planned_amount或total_planned_amount和total_actual_amount之间的较小值
我希望这是有道理的。