查询以识别在 6 个月的时间间隔内超过特定数量的人员

pen*_*jor 3 oracle

我曾尝试在 Google 中搜索,但只是没有找到合适的帖子。我有这张表trans_dateCID其中包含字段、(即 customerid)和amount.

我如何在 6 个月或 180 天的任何时间段内(例如,1 月至 6 月或 2 月至 7 月,或 2014 年 11 月至 2015 年 4 月(期间也重叠年份))从头开始找到超过 1000 美元的 CID时间?

trans_date CID 金额
2015 年 6 月 22 日 123 550
2015 年 8 月 24 日 999 200    
2015 年 8 月 15 日 123 500
2014 年 11 月 24 日 321 200 
2015 年 1 月 8 日 321 900
2015 年 10 月 24 日 999 200     

在结果中,CID 123 和 321 应该是在 6 个月的跨度内都超过总量 1000 的输出。

任何回应将不胜感激。

a_h*_*ame 6

在 6 个月的任何时间段内”这部分让事情变得非常棘手。在特定时期内检查这一点非常容易:

select cid,
       sum(amount)
from transfer
where trans_date >= date '2014-11-01' 
  and trans_date < date '2015-06-01'
group by cid
having sum(amount) >= 1000;
Run Code Online (Sandbox Code Playgroud)

但这不是你想要的。

您需要一个“滚动运行总计”,涵盖过去 6 个月相对于trans_date每一行的值。这可以使用窗口函数(又名“分析函数”)轻松实现

select trans_date, 
       cid, 
       amount,
       sum(amount) over (partition by cid order by trans_date range between interval '6' month preceding and current row) as running_total
from transfer
order by trans_date;
Run Code Online (Sandbox Code Playgroud)

“技巧”是“...之间的范围”部分:它只会评估“过去 6 个月”相对于“当前行”月份的运行总计

以上为您的示例数据返回以下结果:

TRANS_DATE          | CID | AMOUNT | RUNNING_TOTAL
--------------------+-----+--------+--------------
2014-11-24 00:00:00 | 321 |    200 |           200
2015-01-08 00:00:00 | 321 |    900 |          1100
2015-06-22 00:00:00 | 123 |    550 |           550
2015-08-15 00:00:00 | 123 |    500 |          1050
2015-08-24 00:00:00 | 999 |    200 |           200
2015-10-24 00:00:00 | 999 |    200 |           400
Run Code Online (Sandbox Code Playgroud)

现在要获取您感兴趣的客户,您可以将此查询包装到派生表中,然后仅获取那些运行总数至少超过 1000 的 CID:

select distinct cid
from (
  select trans_date, 
         cid, 
         amount,
         sum(amount) over (partition by cid order by trans_date range between interval '6' month preceding and current row) as running_total
  from transfer
) t
where running_total > 1000;
Run Code Online (Sandbox Code Playgroud)

distinct是必要的,因为客户可以有超过一个“6 个月”的总金额超过 1000。

虽然这可能不是最有效的查询 - 但目前我想不出更好的方法。

这是一个 SQLFiddle 示例:http ://sqlfiddle.com/#!4/1e26f/2