Oracle求值的連續範圍

2021-09-02 03:32:29 字數 3196 閱讀 9132

首先帶上原文的鏈結:

有資料如下:

求v_name的連續區間。

期望的結果:

容易理解的寫法:

select v_name,

decode(count(*), 1, to_char(min(id)), min(id) || '-' || max(id)) b

from (select id, v_name, max(rn) over(partition by v_name order by id) rn

from (select id,

v_name,

decode(id - lag(id)

over(partition by v_name order by id),

1,0,

id) rn

from tmp_t))

group by v_name, rn

order by v_name, rn;

簡單的寫法: 

select v_name,

decode(to_char(mi),to_char(ma) ,to_char(ma),to_char(mi) || '-' || to_char(ma)) b

from (select v_name, min(id) mi, max(id) ma

from (select t.* from tmp_t t order by t.v_name, t.id)

group by v_name, id - rownum

order by v_name);

簡潔的寫法: 

--連續id減行號的差值一定是相同的

select v_name,

decode(count(*), 1, to_char(min(id)), min(id) || '-' || max(id)) b

from (select t.*, id - row_number() over(partition by v_name order by id) gp

from tmp_t t)

group by v_name, gp

order by v_name

求連續值範圍一般都是先求差值,在按差值分組,如下所示:

with tmp_t as(

select to_date('201401','yyyy-mm') as v_month,100 as v_value from dual union all

select to_date('201402','yyyy-mm'),100 from dual union all

select to_date('201404','yyyy-mm'),100 from dual union all

select to_date('201405','yyyy-mm'),300 from dual union all

select to_date('201406','yyyy-mm'),100 from dual union all

select to_date('201311','yyyy-mm'),110 from dual union all

select to_date('201310','yyyy-mm'),110 from dual union all

select to_date('201407','yyyy-mm'),100 from dual )

select v_value,decode(to_char(min(v_month), 'yyyymm'),

to_char(max(v_month), 'yyyymm'),

to_char(max(v_month), 'yyyymm'),

to_char(min(v_month), 'yyyymm') || '-' ||

to_char(max(v_month), 'yyyymm')) v_range

from (select v_month,

v_value,

to_number(to_char(add_months(v_month,

-1 * row_number()

over(partition by v_value order by

v_month)),

'yyyymm')) diff

from tmp_t)

group by diff, v_value

order by 1;

結果為:

全文完。

oracle 時間範圍查詢

時間範圍查詢 timestamp 時間查詢select from orders o where o.create time to timestamp 2018 01 21 10 22 58.714000 yyyy mm dd hh24 mi ss.ff and o.create time to ti...

oracle 連續日期統計

select t2.user id,t2.start time,t2.score t2.win coins from select d.user id,d.start time,d.score d.win coins from select user id to char start time,yy...

Oracle連續相同資料的統計

有些事情始終是需要堅持下去的。今天覆習一下之前用到的連續相同資料的統計。首先,建立乙個簡單的測試表,這裡過程就略過了,直接上表 真的是以簡單為主,哈哈 第一種寫法row number select val,count from select id,val,row number over order ...