小编典典

计算来自相同列值的中间行

sql

在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链接我能够得到STARTEND时间,但如何让 行的数量 之间START以及END每个USERID

预期结果

/-------------------------------------------------------\
| UserID ------------------------- Row Count -----------|
| 000001 ------------------------- 2         -----------|
| 000002 ------------------------- 3         -----------|
\-------------------------------------------------------/

阅读 181

收藏
2021-05-16

共1个答案

小编典典

该场景定义不明确,您可以在各种复杂的解决方案中看到它。

这将处理简单的用例。

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
2021-05-16