2016-09-06 59 views
-2

所以我們可以說我有表 - 操作和記錄看起來像這樣的:SQL - 從一個表計數的記錄,使用一個不同的表的日期範圍

動作表:

 
action_id customer start_time  end_time 
101   A   2016-01-01 15:00 2016-01-02 15:00 
102   B   2016-01-01 15:00 2016-01-01 20:00 
103   A   2016-01-01 23:00 2016-01-02 23:00 

記錄表:

 
rec_id customer   time   
1001  A   2016-01-01 16:00 
1002  A   2016-01-01 20:00 
1003  A   2016-01-02 17:00 
1004  B   2016-01-01 15:50 

我想算在START_TIME和第一臺END_TIME內發生的第二個表中的所有記錄,並通過的action_id,客戶羣了。

我的預期輸出應該是:

 
action_id customer count (rec_id)   
101  A    2 
102  B    1 
103  A    1 

感謝所有幫助

+0

你已經嘗試** **什麼感謝 – RiggsFolly

回答

0
select 
    a.action_id,a.customer,count(*) as cnt 
    from 
    records r 
    join 
    Actions a 
    on r.customer=a.customer and 
    r.time between a.start_time and a.end_time 
    group by a.action_id,a.customer 
+0

,但是最終的結果是不顧時間標準(?即使我們定義了它) 所以我使用我的前面的示例Customer A - cnt:3來獲取action_id:101和103 – alon420

相關問題