sql 連續分組判斷 partition by

partition by 會根據分類字段進行排序 加上rownum 能夠造成 每組從1開始從新排序spa

舉個例子, 我要根據時間爲依據,連續出現合併爲一組,統計每組在區間裏的次數code

---------------------------------------------------blog

2010-07-18   2010-07-25   359
2010-06-13   2010-07-11   358
2010-06-06   2010-06-06   359
2010-05-16   2010-05-30   360排序

---------------------------------------------------it

 

能夠用如下代碼實現io

模擬數據table

create table x (weekEndDate char(10), storeCount int);
insert into x values
('2010-07-25',359),
('2010-07-18',359),
('2010-07-11',358),
('2010-07-04',358),
('2010-06-27',358),
('2010-06-20',358),
('2010-06-13',358),
('2010-06-06',359),
('2010-05-30',360),
('2010-05-23',360),
('2010-05-16',360);

排序分組語句class

select min(weekenddate) as startdate, max(weekenddate) as enddate, min(storecount) as storecount 
from 
(select weekenddate, storecount, concat(row_number() over (order by weekenddate) -row_number() over (partition by storecount order by weekenddate),'|',storecount) as groupkey from x) w
group by groupkey order by startdate desc;

 根據普通排序 order by 與 分區排序 partition by 作排序相減 就能夠獲得 新的分組列,咱們就知道按照這個列去獲得咱們要的結果了 date

相關文章
相關標籤/搜索