Oracle Query with Partision,Order and Bucketing

时间:2015-05-29 16:17:45

标签: oracle counting rank

示例数据:

Customer ID  Transaction Date  Code  Expected Bucketing
-----------  ----------------  ----  ----
          1    1/1/2015        254      1
          1    1/2/2015        253      1
          1    1/13/2015       271      1
          1    1/14/2015       271      1
          1    2/1/2015        254      2
          1    2/12/2015       253      2
          1    2/13/2015       271      2
          1    3/1/2015        254      3
          1    3/12/2015       253      3
          1    3/13/2015       271      3
          2    1/1/2015        254      1
          2    1/2/2015        253      1
          2    1/13/2015       271      1
          2    1/14/2015       271      1
          2    2/1/2015        254      2
          2    2/12/2015       253      2
          2    2/13/2015       271      2

我希望Partision by"客户ID"并按"交易日期排序" 每次第一条记录以事务代码254开始。 我必须首先开始计数我发现254(1)直到找到下一个254(然后计为2)。 第四个领域是我想要实现的目标。

有人可以帮助我在Oracle查询中获取数据,如上面的字段4

谢谢

1 个答案:

答案 0 :(得分:1)

解决方案 1 - 自连接查询,其中一个子查询是代码= 254的数据,第二个是休息。 接下来将连接这些子查询,并将第一个的行号分配给第二部分:

with t1 as (
    select cid, tdate td1, code, 
        lead(tdate) over (partition by cid order by tdate) td2,
        row_number() over (partition by cid order by tdate) rn
      from test where code=254),
  t2 as (select cid, tdate, code from test where code<>254)
select t2.cid, t2.tdate, t2.code, t1.rn from t1 
  join t2 on t1.cid = t2.cid 
         and t2.tdate between nvl(t1.td1, t2.tdate) and nvl(t1.td2, t2.tdate)
union all 
select cid, td1, code, rn from t1 order by cid, tdate

SQLFiddle demo

解决方案 2 - 递归查询,可从Oracle 11g版本获得:

with t as (select cid, tdate, code, 
  row_number() over (partition by cid order by tdate) rn from test),
u (cid, td, cd, rn, x) as (
  select cid, tdate, code, rn, 1 from t where rn=1
  union all
  select t.cid, t.tdate, t.code, t.rn, decode(t.code, 254, u.x+1, u.x)
    from u join t on t.cid = u.cid and t.rn = u.rn+1 )
select cid, td, cd, x from u order by cid, td

SQLFiddle demo

两种解决方案都产生了所需的输出,我假设每个客户都设置了代码= 254的行,就像你的例子一样。

有用的链接:function lead(),功能row_number()recursive queries以及最后但并非最不重要的How do I ask a good question?