需求說明:
需要查詢出某個(gè)客戶某一年那些天是有連續(xù)辦理過業(yè)務(wù)
實(shí)現(xiàn)SQL如下:
創(chuàng)建表:
復(fù)制代碼 代碼如下:
create table test_num
(tyear number,
tdate date);
測(cè)試數(shù)據(jù):
insert into test_num
select 2014,trunc(sysdate)-1 from dual union all
select 2014,trunc(sysdate)-002 from dual union all
select 2014,trunc(sysdate)-003 from dual union all
select 2014,trunc(sysdate)-004 from dual union all
select 2014,trunc(sysdate)-005 from dual union all
select 2014,trunc(sysdate)-007 from dual union all
select 2014,trunc(sysdate)-008 from dual union all
select 2014,trunc(sysdate)-009 from dual union all
select 2013,trunc(sysdate)-120 from dual union all
select 2013,trunc(sysdate)-121 from dual union all
select 2013,trunc(sysdate)-122 from dual union all
select 2013,trunc(sysdate)-124 from dual union all
select 2013,trunc(sysdate)-125 from dual union all
select 2013,trunc(sysdate)-127 from dual union all
select 2015,trunc(sysdate)-099 from dual union all
select 2015,trunc(sysdate)-100 from dual union all
select 2015,trunc(sysdate)-101 from dual union all
select 2015,trunc(sysdate)-102 from dual union all
select 2015,trunc(sysdate)-104 from dual union all
select 2015,trunc(sysdate)-105 from dual;
寫SQL:
復(fù)制代碼 代碼如下:
SELECT TYEAR, MIN(TDATE) AS STARTDATE, MAX(TDATE), COUNT(TYEAR) AS ENDNUM
FROM (SELECT A.*, A.TDATE - ROWNUM AS GNUM
FROM (SELECT * FROM TEST_NUM ORDER BY TYEAR, TDATE) A)
GROUP BY TYEAR, GNUM
ORDER BY TYEAR, MIN(TDATE)
您可能感興趣的文章:- SQL查詢連續(xù)號(hào)碼段的巧妙解法
- 連續(xù)序號(hào)的 sql語句