Oracle計算連續登陸/上班天數

來源:互聯網
上載者:User

Oracle計算連續登陸/上班天數

現在有一個計算使用者連續上班天數的報表,發現通過用row_number分析函數可以完美計算這個問題。這個SQL可以解決計算使用者連續登陸、簽到、上班、曠工等問題。

首先將row_number按照日期排序

將日期的日,比如2016-7-1,將1截取出來轉換成數字

把這個日期數字減去row_number計算出來值,作為分組號,因為不連續的值算出來的分組號就不一致;

根據分組號欄位進行group by,可以算出每段連續上班的開始、結束時間、天數

如原資料是這樣的
2016/7/1
2016/7/2
2016/7/4
2016/7/5
2016/7/6
2016/7/7
……

計算出來的結果是
分組號  開始時間    結束時間    天數
0    2016/7/1    2016/7/2    2
1    2016/7/4    2016/7/9    6
……

下面上代碼
with t1 as
(
select date'2016-7-1' d1 from dual
union
select date'2016-7-2' d1 from dual
union
select date'2016-7-4' d1 from dual
union
select date'2016-7-5' d1 from dual
union
select date'2016-7-6' d1 from dual
union
select date'2016-7-7' d1 from dual
union
select date'2016-7-8' d1 from dual
union
select date'2016-7-9' d1 from dual
union
select date'2016-7-11' d1 from dual
union
select date'2016-7-12' d1 from dual
union
select date'2016-7-13' d1 from dual
union
select date'2016-7-14' d1 from dual
union
select date'2016-7-18' d1 from dual
union
select date'2016-7-19' d1 from dual
)
select gn,min(d1),max(d1),count(*)
from(
select d1,to_number(to_char(d1,'dd'))-row_number() over(order by d1) gn from t1
)group by gn order by 2

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.