我正在尝试计算表中只有一个会话的唯一事件数。我们有一个名为会话跟踪的表,用于存储事件编号,还存储该会话的先前状态和当前状态。我想得到只有一个会话的事件数量,并且我还要计算可能有多个会话的事件数量,但前提是以下会话以关闭结束并结束关闭。基本上不计算它们不会在聚合列表中更改状态的会话。
示例:
Incident ID Start Status End Status
1 Open Closed
1 Closed Closed
2 Open Closed
3 Open Closed
4 Open Open
4 Open Closed
我想获得前三个事件,因为事件2和3每个只有一个会话,并且想要计算第一个事件,因为它在已经关闭后有一个会话,而第二个会话不计算。第四起事件将不会被计算在内,因为它有一个以上的会议开放。
这是我正在使用的声明,并认为某些事情可能已经消失......
SELECT Incident, COUNT(Incident)
FROM Session_Tracking
WHERE NOT (Prev_Status = 'Closed' AND Current_Status = 'Closed')
GROUP BY Incident
HAVING COUNT(Incident) = 1
答案 0 :(得分:2)
假设您正在使用支持窗口函数的合理数据库,您可以通过计算:
来完成此操作select SUM(case when numInIncident = 1 then 1 else 0 end) as Singletons,
SUM(case when ClosedClosed = numInIncident - 1 and numInINcident > 1 then 1 else 0
end) as RestClosed
from (select st.*,
COUNT(*) over (partition by incident) as numInIncident,
sum(case when startStatus = 'Closed' and endStatus = 'Closed' then 1 else 0 end) over (partition by incident) as ClosedClosed
from session_tracking
) st
内部子查询计算每个事件的行数,以及当开始和结束状态都“关闭”时的数量行数。外部查询应用此逻辑来获取您想要的数字。