0

我想制作一个特定的计数器,在连续找到特定记录后将加一。

  time    event      revenue   counter

 13.37    START        20          1  
 13.38   action A      10          1  
 13.40   action B       5          1  
 13.42      end                    1  

 14.15    START        20          2  
 14.16   action B       5          2  
 14.18     end                     2  

 15.10    START        20          3  
 15.12     end                     3  

我需要找出每次访问的总收入(START 和 END 之间的操作)。我在想最好的方法是设置这样的计数器:

所以我可以对活动进行分组。但如果您有更好的解决方案,我将不胜感激。

4

2 回答 2

0

You can use a query similar to the following:

with StartTimes as
(
  select time,
    startRank = row_number() over (order by time)
  from events
  where event = 'START'
)
select e.*, counter = st.startRank
from events e
  outer apply
  (
    select top 1 st.startRank
    from StartTimes st
    where e.time >= st.time
    order by st.time desc
  ) st

SQL Fiddle with demo.

May need to be updated based on the particular characteristics of the actual data, things like duplicate times, missing events, etc. But it works for the sample data.

于 2013-03-24T01:01:41.483 回答
0

SQL Server 2012 supports an OVER clause for aggregates, so if you're up to date on version, this will give you the counter you want:

count(case when eventname='START' then 1 end) over (order by eventtime)

You could also use the latest START time instead of a counter to group by, like this:

with t as (
  select
  *,
  max(case when eventname='START' then eventtime end)
    over (order by eventtime) as timeStart
  from YourTable
)
  select
    timeStart,
    max(eventtime) as timeEnd,
    sum(revenue) as totalRevenue
  from t
  group by timeStart;

Here's a SQL Fiddle demo using the schema Ian posted for his solution.

于 2013-03-24T01:04:00.663 回答