2017-10-12 132 views
2

我试图在Oracle上运行查询。我有一个帐户结算付款表,我有一个查询,可以查看最后三笔结算金额,以及任何已注销的金额,用于我需要此信息的任何帐户。SQL Oracle /聚合查询

但是,一些帐户是以每周为基础的,对于这些帐户,我想将他们的每周结算汇总到他们的月度小组中。这里是我的代码至今:

SELECT * 
FROM  (
    SELECT * 
    FROM (
      SELECT gwod.account_id, 
        gwod.charge_period_start, 
        SUM(gwod.total_due_on_charge) total_due_on_charge, 
        SUM(gwod.amount_written_off) amount_written_off, 
        DENSE_RANK() over (PARTITION BY gwod.account_id 
             ORDER BY charge_period_start DESC) rownumber 
      FROM  report.accounts_write_off gwod 
      WHERE account_id IN (‘account_number’) 
      GROUP BY gwod.account_id, 
        gwod.charge_period_start 
      HAVING SUM (gwod.total_due_on_charge) <> 0) t1 
    WHERE t1.rownumber <=3) 
    PIVOT (MAX(charge_period_start) charge_period, 
      MAX(total_due_on_charge) total_due_on_charge, 
      MAX(amount_written_off) amount_written_off 
      FOR rownumber IN (1,2,3)) 
ORDER BY account_id.* 

这工作完全但每周根据账户,因此而不是通过过去三年每周量来进行结算拉动,即25-09-17,18-09 -17,2017年9月9日,我想通过9月,8月和7月的总计付款。

我希望这一切都有道理。

回答

0

只需将聚集来自当前单元的水平(即,每周)给月水平EXTRACT(month ...)在内部查询的SELECTGROUP BY以及PARTITIONPIVOT条款修改:

SELECT * 
FROM  (
    SELECT * 
    FROM (
      SELECT gwod.account_id, 
        EXTRACT(month FROM gwod.charge_period_start) charge_period_month, 
        SUM(gwod.total_due_on_charge) total_due_on_charge, 
        SUM(gwod.amount_written_off) amount_written_off, 
        DENSE_RANK() over (PARTITION BY gwod.account_id 
             ORDER BY EXTRACT(month FROM gwod.charge_period_start) DESC) rownumber 
      FROM  report.accounts_write_off gwod 
      WHERE account_id IN ('account_number') 
      GROUP BY gwod.account_id, 
        EXTRACT(month FROM gwod.charge_period_start) 
      HAVING SUM (gwod.total_due_on_charge) <> 0) t1 
    WHERE t1.rownumber <=3) 
    PIVOT (MAX(charge_period_month) charge_period, 
      MAX(total_due_on_charge) total_due_on_charge, 
      MAX(amount_written_off) amount_written_off 
      FOR rownumber IN (1,2,3)) 
ORDER BY account_id.* 

DEMO(随机数据)

http://rextester.com/UJK84858

+0

我公顷在Oracle中没有看到MONTH()函数,您在哪里找到它? – mathguy

+0

Oracle数据库中没有MONTH()函数。您发布的链接是用于JAVADB的。我不需要尝试EXTRACT(...),我知道它会起作用 - 这是在Oracle中执行此操作的正确方法。 – mathguy

+0

另外 - 你的意思是“我的”表测试?我不是OP。 – mathguy