2012-05-08 47 views
1

我正在使用SQL Server 2005.我試圖計算在15分鐘和14天之間的重複次數,當客戶端和類型是相同的。SQL Server - 計算從基準時間起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倍因爲客戶端和類型必須相同,因爲我需要按天過濾。

謝謝。

+0

一些想法,讓你開始:在一個日期範圍,您可以自行加入。你可以使用'SUM(Case ...)作爲條件計數。 – JNK

+0

嘗試使用HAVING COUNT(Type)> 1對子查詢進行計數,但我無法弄清楚如何使用日期範圍我想。謝謝 – Brad

+0

你如何定義一個重複?這兩行必須有相同的ID和Type值嗎?它是一個日期在第二個日期的14天內嗎?它是一個日期在15分鐘另一個日期?是一個日期大於15分鐘但不是14天嗎? – Thomas

回答

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 Fiddle

+0

我明白這是如何工作的,但是sql server 2005沒有像使用CAST(eci_date as date)那樣使用DATE的能力。感謝您的所有幫助到目前爲止 – Brad

+0

@Brad - 輕鬆解決。稍後修復 – Thomas

+0

@Brad - 修正了這個問題,它將在SQL 2005中工作 – Thomas

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)來提取一個日期時間的日期部分。

相關問題