【问题标题】:Monthly Costs to be received Query - Oracle 11g每月接收费用查询 - Oracle 11g
【发布时间】:2013-05-17 13:53:47
【问题描述】:

在 Oracle 11g 数据库中,我有以下表格,其中包含:

1) 将由合作者开具发票的计划每月费用。

MONTH:每月权限的费用

AMOUNT:与本月相关的费用金额

2) 协作者收到的月度发票金额。

MONTH:发票的每月权限

AMOUNT:与本月相关的发票金额

考虑这个例子:

表 1(计划成本):

2013 年 1 月 10,000
2013 年 2 月至 2013 年 10,000
2013 年 3 月 10,000
2013 年 4 月 10,000
2013 年 5 月 10,000
2013 年 6 月 10,000

表 2(实际发票):

2013 年 3 月 35,000

查询结果应该是:

2013 年 4 月 5,000
2013 年 5 月 10,000
2013 年 6 月 10,000

有什么提示吗?

谢谢 威尔·E。

【问题讨论】:

  • 每月是否会有多个成本或发票记录?换句话说,在应用计算之前是否需要按月求和才能得到结果?此外,如果您现在还涉及其他列,是时候展示它们了 - 对此的答案将是一些涉及到的分析查询,如果有任何分组或其他特殊要求,最好立即知道它们。

标签: oracle


【解决方案1】:

根据您提供的信息,以下查询应该会生成您想要的结果。

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 并且每个月返回 lesser i>planned_amount,total_planned_amounttotal_actual_amount

之间的差额

我希望这是有道理的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    相关资源
    最近更新 更多