在Microsoft SQL Server中,如何根据同一列中的值计算中间行。
/-----------------------------------------\ | ID ---------- Event -------- UserID ----| | 1 ----------- START -------- 000001 ----| | 2 ----------- START -------- 000002 ----| | 3 ----------- END -------- 000001 ----| | 4 ----------- PL -------- 000002 ----| | 5 ----------- END -------- 000002 ----| \-----------------------------------------/
考虑为UserID000002,是2,基于此查询4&5,具有本3行和ID链接我能够得到START和END时间,但如何让 行的数量 之间START以及END每个USERID
UserID
START
END
USERID
预期结果
/-------------------------------------------------------\ | UserID ------------------------- Row Count -----------| | 000001 ------------------------- 2 -----------| | 000002 ------------------------- 3 -----------| \-------------------------------------------------------/
该场景定义不明确,您可以在各种复杂的解决方案中看到它。
这将处理简单的用例。
select UserID ,count(*) as cnt from mytable
这将处理复杂的用例。
select UserID ,min(ID) as from_ID ,max(ID) as to_ID ,count(*) as events from (select UserID,ID,Event , count(case when Event in ('START','END') then 1 end) over ( partition by UserID order by Id rows unbounded preceding ) - case when Event = 'END' then 1 else 0 end as group_seq from mytable ) t group by UserID ,group_seq having min(case when Event = 'START' then 1 end) = 1 order by UserID ,from_id