SQL - mutliple条件的两个日期之间的实例计数

时间:2017-02-16 14:45:00

标签: sql count

我有一个包含日期范围的帐号表。我必须使用另一个数据表来确定我们在日期范围之间与该帐户进行了多少次交互。我甚至无法开始。

表1

+------+------------+------------+  
| Acct |  EndDate   | StartDate  |  
+------+------------+------------+  
|    1 | 2017-02-14 | 2016-12-16 |  
|    2 | 2017-02-14 | 2016-12-16 |  
|    3 | 2017-02-13 | 2016-12-15 |  
+------+------------+------------+  

表2

+------+--------------+
| acct | calllog_date |
+------+--------------+
|    1 | 2016-06-16   |
|    1 | 2016-08-15   |
|    1 | 2015-11-10   |
|    2 | 2015-11-10   |
|    2 | 2015-11-13   |
|    2 | 2015-11-16   |
|    2 | 2015-11-19   |
|    3 | 2015-11-19   |
|    3 | 2015-11-23   |
|    4 | 2015-11-30   |
+------+--------------+

1 个答案:

答案 0 :(得分:0)

根据日期值之间的匹配项尝试使用JOIN

SELECT t1.Acct, COUNT(*) AS cnt
FROM Table1 AS t1
JOIN Table2 AS t2 
   ON t1.Acct = t2.Acct AND t2.calllog_date BETWEEN t1.StartDate AND t1.EndDate
GROUP BY t1.Acct