ROWNUM 應用案例 實現乙個拉鍊表

2022-07-01 06:54:18 字數 3323 閱讀 3580

有以下資料表:事件標識表未這**票進入(1)或者移除(2)某**票池。我們需要對資料進行去重,就是連續多次的進入,或者連續多次的移除,都只取第一次的日期。

如圖中,黃色的記錄是不需要的。(這個表命名為demo)

首先第一步

select

scode,poolid,effective_day,adjustmode

,row_number()

over (partition by scode,poolid,adjustmode order

by effective_day) as

rn ,row_number()

over (partition by scode,poolid order

by effective_day) as

rn2

from demo t

得到如下結果(我將進入的標註了紅色):

觀察資料的規律,然後我們用rn2-rn1。再按scode+poolid+adjustmode分組中,按日期進行排序。

然後發現rn3=1的就是我們需要的記錄.

完整的**如下:

with demo as (

select '00001' as scode,1 poolid,date'2010-01-01' as effective_day,1 as adjustmode from dual

union all

select '00001' as scode,1 poolid,date'2010-01-03' as effective_day,1 as adjustmode from dual

union all

select '00001' as scode,1 poolid,date'2010-01-05' as effective_day,2 as adjustmode from dual

union all

select '00001' as scode,1 poolid,date'2010-01-07' as effective_day,2 as adjustmode from dual

union all

select '00001' as scode,1 poolid,date'2010-02-01' as effective_day,1 as adjustmode from dual

union all

select '00001' as scode,1 poolid,date'2010-02-03' as effective_day,1 as adjustmode from dual

union all

select '00001' as scode,1 poolid,date'2010-02-07' as effective_day,2 as adjustmode from dual

union all

select '00002' as scode,1 poolid,date'2010-01-01' as effective_day,1 as adjustmode from dual

union all

select '00002' as scode,1 poolid,date'2010-01-05' as effective_day,2 as adjustmode from dual

union all

select '00002' as scode,1 poolid,date'2010-01-07' as effective_day,2 as adjustmode from dual

union all

select '00002' as scode,1 poolid,date'2010-02-01' as effective_day,1 as adjustmode from dual

union all

select '00002' as scode,1 poolid,date'2010-02-03' as effective_day,1 as adjustmode from dual

union all

select '00002' as scode,1 poolid,date'2010-02-07' as effective_day,2 as adjustmode from dual

)  ,data as (

select x.*,rn2-rn,row_number() over (partition by scode,poolid,adjustmode,rn2-rn order by rn) as rn3

from (      

select scode,poolid,effective_day,adjustmode

,row_number() over (partition by scode,poolid,adjustmode order by effective_day) as rn

,row_number() over (partition by scode,poolid order by effective_day) as rn2

from  demo t

) x)

select * from data where rn3=1

order by 1,2,3

函式計算實踐 乙個應用案例

來自乙個使用者匹配的需求。使用者的不同資訊分布於兩個系統,且客觀上無法直接打通。所以就涉及到兩個系統id匹配的問題。先抽象問題 系統a,系統b 系統a中存在乙個使用者a 字段 a id,a img,a name 系統b中可能有a的補充資訊 字段 ab id,ab img,ab name 目標 如果b...

乙個string類的簡單實現案例

string類中使用到了賦值建構函式 複製建構函式 建構函式 預設建構函式 析構函式 過載操作符等一些類操作 class string string const char str string const char str,int n string const string src 拷貝建構函式 也...

oracle 中使用 rownum 的乙個誤區

一 首先看乙個簡單的測試 1 建立乙個簡單的 test 表,裡面插入 1 9 條資料 2 按照 status 字段進行排序,得到的結果 3 使用 rownum 取前 5 條結果 二 測試中的兩個問題 1 上面第二步中,select 出來的結果,第 5 條記錄的 userid 不是 5,而是 9 原因...