2

我有用户登录应用程序时生成的数据。它包含带时间戳的登录和注销,不属于任何特定的工作活动。这些是我对每条记录的界限。

在那个时间范围内,我有可重复的动作,任务 1、任务 2、休息等,这些都归因于一个活动。

为了开始另一个活动,用户必须注销并重新登录应用程序,这将重新开始该过程。

在这个小提琴中,我已经布置了表格和示例数据,并且我第一次尝试收集数据,但是通过这种方法,登录/注销的开始和停止时间被加在一起,但我需要数据来反映开始并停止竞选活动的时间,我不知道该怎么做。

http://sqlfiddle.com/#!3/5347c/1

我的结果需要包括:

  • 活动
  • 鼻祖
  • 开始(从该集合的登录操作开始的时间)
  • 结束(从该集合的注销操作开始的时间)
  • 集合的任务 1 的总和
  • 集合的任务 2 的总和
  • 该集的最后一个任务

    ══════════════════════════════════════════════════
    Campaign Originator Start End   Task1 Task2 LastAction
    ═══════════════════════════════════════════════════
    Camp1    1000       08:00 09:27 3120  855    Logout   
    Camp2    1000       09:30 10:32 1800  135    Logout   
    Camp1    1000       13:00 0        0         Task1    
    

我尝试使用 CTE 方法将登录和注销时间作为单独的行来获取,但由于我不确定下一步,所以我陷入了一个混乱的圈子。

有人可以分享一下我如何通过这些数据获得这些结果吗?

4

1 回答 1

1

这可能需要一些重构:

;with Sessions as (
    select OriginatorId, State, Duration, ActionLocalTime, Campaign
        -- Get an id that will later be used to find the max row per session. Break ties with logical State order.
        , row_number() over (order by OriginatorId, ActionLocalTime, case State when 'Login' then 10 when 'Logout' then 30 else 20 end, State) as RowNum
        -- Get a Session id for each login
        , (select count(*) from Actions where State = 'Login' and OriginatorID = a.OriginatorID and ActionLocalTime <= a.ActionLocalTime) as Session
    from Actions a
), Campaigns as (
    select OriginatorId, State, Duration, ActionLocalTime, RowNum
        -- Get the Campaign for this session
        , (select max(Campaign) from Sessions where OriginatorID = s.OriginatorID and Session = s.Session) as Campaign
    from Sessions s
)
select Campaign
    , OriginatorID as Originator
    , min(ActionLocalTime) as Start
    , (select ActionLocalTime from Sessions where RowNum = max(c.RowNum) and State = 'Logout') as [End]
    , (select sum(Duration) from Campaigns where OriginatorID = c.OriginatorID and Campaign = c.Campaign and State = 'Task 1') as Task1
    , (select sum(Duration) from Campaigns where OriginatorID = c.OriginatorID and Campaign = c.Campaign and State = 'Task 2') as Task2
    , (select State from Sessions where RowNum = max(c.RowNum)) as LastAction
from Campaigns c
group by OriginatorID, Campaign
order by OriginatorID, Campaign

输出:

Campaign Originator Start                   End                     Task1 Task2 LastAction
-------- ---------- ----------------------- ----------------------- ----- ----- ----------
Camp1    1000       2013-05-06 08:00:00.000 2013-05-06 09:27:00.000 3120  855   Logout
Camp2    1000       2013-05-06 09:30:00.000 2013-05-06 10:32:00.000 1800  135   Logout

这是一个带有一些额外数据的SQL Fiddle 。

于 2013-05-06T21:12:45.530 回答