【发布时间】: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
【问题讨论】: