我正在使用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必须相同,因为我需要按天过滤。
谢谢。
答案 0 :(得分: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
答案 1 :(得分: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)
从日期时间中提取日期部分。