以下為例子數據 圖1
圖1
首先根據要求取出BeforeMeal要在7.0以下 並且 bingAfterMeal要在11.1以下
select AccountId,CreateTime from DiabetesRecord where BeforeMeal < 7.0 and AfterMeal < 11.1 group by AccountId,CreateTime
得到以下數據如圖2
圖2
把連續的天數進行分組
select *,((select count(1) from (select AccountId,CreateTime from DiabetesRecord where BeforeMeal < 7.0 and AfterMeal < 11.1 group by AccountId,CreateTime)dr2 where dr1.AccountId = dr2.AccountId and dr2.CreateTime <= dr1.CreateTime) - day(dr1.CreateTime)) as 'rownum' from (select AccountId,CreateTime from DiabetesRecord where BeforeMeal < 7.0 and AfterMeal < 11.1 group by AccountId,CreateTime)dr1
結果如圖3所示
圖3
按用戶 、開始時間、結束時間 和 連續天數分組
select AccountId,min(CreateTime),max(CreateTime),(datediff(max(CreateTime),min(CreateTime))+1) as 'rn' from
(select *,((select count(1) from (select AccountId,CreateTime from DiabetesRecord where BeforeMeal < 7.0 and AfterMeal < 11.1 group by AccountId,CreateTime)dr2 where dr1.AccountId = dr2.AccountId and dr2.CreateTime <= dr1.CreateTime) - day(dr1.CreateTime)) as 'rownum' from (select AccountId,CreateTime from DiabetesRecord where BeforeMeal < 7.0 and AfterMeal < 11.1 group by AccountId,CreateTime)dr1)z group by AccountId,rownum
得到如圖4所示
圖4