2015-05-29 72 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?