【问题标题】:Get last 6 month data, If data is not available then print monthname and 0获取最近 6 个月的数据,如果数据不可用,则打印月份名称和 0
【发布时间】:2016-09-03 08:55:26
【问题描述】:

我正在尝试从 oracle DB 获取最近 6 个月的数据。我只有在数据存在时才能获取月份数据,我的要求是获取所有六个月的数据,如果数据不存在,则查询应返回月份名称和值 0。

预期结果

1000 年 1 月
2 月 0 日
3 月 0 日
4 月 0 日
1200 年 5 月

得到结果
1000 年 1 月
1200 年 5 月

以下是我想要得到的查询。

select
  to_char(trunc(td.cre_on_date,'MON'), 
 'Month',
 'nls_date_language=american') TDATE ,
 coalesce(sum(td.amt),0) amt
from  trandetail td, tranheader th 
where th.batchid = td.batchid 
and td.status = 'FDSC' 
and td.ccy = 'USD' 
and th.pcid in (
  (select pty_id from bus_pty_hier bh 
    inner join bus_pty bp on bh.ASSOC_BUS_PTY_ID = BP.PTY_ID
    START WITH PARNT_BUS_PTY_ID = 1 
    CONNECT BY PRIOR ASSOC_BUS_PTY_ID = PARNT_BUS_PTY_ID) 
  union select 1 from dual) 
and td.cre_on_date > trunc(sysdate-180)
GROUP BY trunc(td.cre_on_date,'MON') 
ORDER BY trunc(td.cre_on_date,'MON') asc

【问题讨论】:

    标签: oracle oracle10g


    【解决方案1】:

    您无法从数据中获取另外四个月,因为它们不存在。您需要生成潜在月份的列表,然后外部连接到您的数据。类似(未经测试):

    with months (month) as (
      select add_months(trunc(sysdate, 'MM'), -1 * (level - 1))
      from dual
      connect by level <= 6
    )
    select to_char(m.month, 'Month', 'nls_date_language=american') TDATE,
      coalesce(sum(t.amt),0) amt
    from months m
    left join (
      select trunc(td.cre_on_dt, 'MM') as month, td.amt
      from trandetail td
      inner join tranheader th 
      on th.batchid = td.batchid 
      where td.status = 'FDSC' 
      and td.ccy = 'USD' 
      and th.pcid in (
        select pty_id
        from bus_pty_hier bh 
        inner join bus_pty bp
        on bh.ASSOC_BUS_PTY_ID = BP.PTY_ID
        START WITH PARNT_BUS_PTY_ID = 1 
        CONNECT BY PRIOR ASSOC_BUS_PTY_ID = PARNT_BUS_PTY_ID
        union select 1 from dual
      )
      and td.cre_on_date >= add_mknths(trunc(sysdate), -6) -- maybe trunc MM again
    ) t
    on t.month = m.month
    GROUP BY m.month
    ORDER BY m.mknth
    

    months CTE 给出了过去六个月中每个月的第一天。我基本上已将您的大部分原始查询放入内联视图(但它可能是另一个 CTE),因为它有自己的连接,但您可能可以解开它,所以这确实是一个起点。从该内联视图中,您可以获取每笔交易的月份和金额,并且在聚合和合并完成之前将它们外部加入到妈妈的主列表中。

    【讨论】:

    • 感谢 Alex 的帮助,现在我收到错误 ''ORA-00904: "TD"."AMT": invalid identifier,你能帮忙解决这个问题吗?
    • @user1127643 - 好吧,我说它未经测试 *8-) 我没有更改总和中的表别名。已更新。
    猜你喜欢
    • 1970-01-01
    • 2022-07-13
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2016-12-19
    相关资源
    最近更新 更多