【发布时间】:2013-02-08 17:15:14
【问题描述】:
我需要根据他们的收入贡献期在一个月内获得活跃的客户数量。
原始数据:
ACCOUNT_ID REVENUE_START_DATE REVENUE_END_DATE
1234 1/14/2010 0:00 4/13/2010 23:59
4567 2/9/2010 0:00 3/8/2010 23:59
1234 5/9/2010 0:00 6/8/2010 23:59
预期结果
Month Count
Dec-09 0
Jan-10 1
Feb-10 2
Mar-10 2
Apr-10 1
May-10 1
Jun-10 1
Jul-10 0
Aug-10 0
Sep-10
Oct-10
以下是我处理的 Oracle 代码(在 google 的帮助下),但由于日期重叠,我没有得到正确的结果。我请求专家帮助我解决这个问题。 (提前致谢)
当前结果:
YEAR_ MONTH_ ACT
2010 January 2
2010 February 3
2010 March 3
2010 April 3
甲骨文代码:
with tab as
(
select distinct ACCOUNT_ID, billing_start_date as revenue_start_date, billing_end_date as revenue_end_date
from accounts
),
year_tab as
(
select
add_months(min_date, level -1) m
from
(
select min(trunc(revenue_start_date,'YYYY')) min_date, add_months(max(trunc(revenue_end_date,'YYYY')), 12) max_date
from tab
)
connect by level <= months_between(max_date, min_date)
)
select to_char(m,'YYYY') year_,
to_char(m,'Month') month_,
nvl(act, 0) act
from year_tab,
(
select m date_,count(*) act
from tab, year_tab
where m between trunc(revenue_start_date,'MM') and trunc(revenue_end_date,'MM')
group by m
) month_tab
where m = date_(+)
order by m;
【问题讨论】:
-
我得到了你的预期结果(除了它显示了 2010 年的所有月份,而不是 2009 年 12 月到 2010 年 10 月)。我不太确定问题是什么...您确定您的示例数据是您实际使用的(尤其是因为列名使用您的
tab别名)。 -
嗨,Alex.. 感谢您查看代码。我在这里发现的问题是,在 1 月 10 日期间,收入仅由帐户 ID“1234”产生,但此查询的结果显示 2,类似地,对于 2 月份,收入由帐户 ID“1234”产生和“4567”,但查询显示 3。我完全不确定原因..你能帮帮我吗?..
-
但是当我用你的三行数据创建一个
accounts表时,你的查询按预期给了我1,2,2,1,1,1。这张照片少了点什么…… -
可能是我遗漏了一些我无法解释的东西。请从我提供原始数据和结果的以下链接下载电子表格。 citrix.sharefile.com/d-sd5a1f9ef4f54fbd8