1

我正在使用 SQL Server 2005。当客户端和类型相同时,我正在尝试计算 15 分钟到 14 天之间的重复次数。

表 [交互] 看起来像:

eci_date                 user_ID  Type  Client
2012-05-01 10:29:59.000  user1    12    14
2012-05-01 10:35:04.000  user1    3     15
2012-05-01 10:45:14.000  user3    4     14
2012-05-01 11:50:22.000  user1    5     15
------------------------------------------
2012-05-02 10:30:28.000  user2    12    14
2012-05-02 10:48:59.000  user5    12    14
2012-05-02 10:52:23.000  user2    12    15
2012-05-02 12:49:45.000  user8    3     14
------------------------------------------
2012-05-03 10:30:47.000  user4    5     15
2012-05-03 10:35:00.000  user6    4     12
2012-05-03 10:59:10.000  user7    4     12

我希望输出看起来像:

eci_date    Type  Total_Calls  Total_Repeats
2012-05-01  12    1            2
2012-05-01  3     1            0
2012-05-01  4     1            0
2012-05-01  5     1            1
---------------------------------------------
2012-05-02  12    3            0
2012-05-02  3     1            0
---------------------------------------------
2012-05-03  4     2            1
2012-05-03  5     1            0

所以会有 2 次重复,因为客户端 14 在他们第一次调用之后调用了 2 次,因为 Client 和 Type 必须相同并且因为我需要按天过滤。

谢谢你。

4

2 回答 2

2
With Metrics As
  (
  Select T1.Client, T1.Type
    , Min(eci_Date) As FirstCallDate
  From Table1 As T1
  Group By T1.Client, T1.Type
  )
Select DateAdd(d, DateDiff(d,0,T1.eci_date), 0) As [Day], Type, Count(*) As TotalCalls
  , (
    Select Count(*)
    From Table1 As T2
      Join Metrics As M2
        On M2.Client = T2.Client
          And M2.Type = T2.Type
    Where T2.eci_Date >= DateAdd(mi,15,M2.FirstCallDate)
      And T2.eci_date <= DateAdd(d,15,M2.FirstCallDate)
      And DateAdd(d, DateDiff(d,0,T1.eci_date), 0) = DateAdd(d, DateDiff(d,0,T2.eci_date), 0)
    ) As Total_Repeats
From Table1 As T1
Group By DateAdd(d, DateDiff(d,0,T1.eci_date), 0), Type
Order By [Day] Asc, Type Desc

SQL小提琴

于 2012-05-08T15:55:40.673 回答
0

您的问题含糊不清,因此我将其解释为以下含义: *“total_count”列是给定日期不同用户的数量 *重复次数是接下来 14 次中第一个之后的呼叫次数天

以下查询完成此操作:

select eci_date, count(distinct id) as numusers, count(*) as Total_repeats
from 
(
  select cast(eci_date as date) as eci_date, 
     id, 
     count(*) as total,
     min(eci_date) as firstcall
  from table t
  group by cast(eci_date as date), user_id
) t 
left outer join table t2
  on t.user_id = t2.user_id 
  and t2.eci_date between firstcall and dateadd(day, 14, firstcall) 
  and t2.eci_date <> firstcall
group by eci_date

请注意,这使用语法cast(<datetime> as date)从日期时间中提取日期部分。

于 2012-05-08T14:35:41.963 回答