select ID,
statusid,
Status,
max(case when rn_grp_asc=1 then statusdate end) as frst_time_first_status,
max(case when rn_grp_desc=1 then statusdate end) as last_time_first_status,
count(distinct grp) as unique_times_in_status
from ( select t.*,
row_number() over(partition by id,statusid order by grp,statusdate) as rn_grp_asc,
row_number() over(partition by id,statusid order by grp desc,statusdate) as rn_grp_desc
from ( Select ID,
StatusID,
Status,
StatusDate,
row_number() over(partition by id order by Systemdate)-row_number() over(partition by id,statusid order by Systemdate) as grp
from t
where ID=100
) t
) t
group by id,statusid,Status
上面的查询返回正确的结果,但下面的查询没有。
select ID,
statusid,
Status,
max(case when rn_grp_asc=1 then statusdate end) as frst_time_first_status,
max(case when rn_grp_desc=1 then statusdate end) as last_time_first_status,
count(distinct grp) as unique_times_in_status
from ( select t.*,
row_number() over(partition by id,statusid order by grp,statusdate) as rn_grp_asc,
row_number() over(partition by id,statusid order by grp desc,statusdate) as rn_grp_desc
from ( Select ID,
StatusID,
Status,
StatusDate,
row_number() over(partition by id order by Systemdate)-row_number() over(partition by id,statusid order by Systemdate) as grp
from t
) t
) t
where ID=100
group by id,statusid,Status