2015-05-29 88 views
-1

样本数据:Oracle查询与Partision,订单和桶装

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 

我想通过“客户ID”和排序“交易日期” 每次第一个纪录,交易代码254 我开始Partision必须从第一次开始计算我发现254(1)直到找到下一个254(然后算作2)。 第四场是我想要实现的。

有人可以帮助我在Oracle查询得到上述

感谢

回答

1

解决像场4个数据 - 自联接查询,其中子查询之一是代码= 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


解 - 递归查询,可从Oracle版本11克:

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?