我一直在研究这个看似简单的问题一段时间,但没有解决方案,假设我有一个包含日期列表的表,以及另一个包含电话号码、人员和日期的表,我需要有一个包含所有姓名和所有日期的最终结果,第三列具有在任何日期中出现的唯一电话号码的数量,该日期与结果,这是一个示例:
t1
+------------+
| date |
+------------+
| 01/01/2020 |
| 01/02/2020 |
| 01/03/2020 |
| 01/04/2020 |
| 01/05/2020 |
| 01/06/2020 |
| 01/07/2020 |
| 01/08/2020 |
+------------+
t2
+------+------------+--------------+
| name | date | phone_number |
+------+------------+--------------+
| John | 01/01/2020 | 123 |
| Mike | 01/02/2020 | 456 |
| Mike | 01/03/2020 | 789 |
| John | 01/04/2020 | 999 |
| Mike | 01/05/2020 | 111 |
| John | 01/06/2020 | 777 |
| Mike | 01/07/2020 | 123 |
| Mike | 01/08/2020 | 456 |
| John | 01/01/2020 | 789 |
| John | 01/02/2020 | 789 |
| Mike | 01/03/2020 | 789 |
| John | 01/04/2020 | 789 |
+------+------------+--------------+
我的目标结果:
+------+------------+-----------------------------------------------------------------+
| Name | Month | Comulative Unique Numbers (Unique Numbers in any date >= Month) |
+------+------------+-----------------------------------------------------------------+
| John | 01/01/2020 | 4 |
| John | 01/02/2020 | 3 |
| John | 01/03/2020 | 3 |
| John | 01/04/2020 | 3 |
| John | 01/05/2020 | 1 |
| John | 01/06/2020 | 1 |
| John | 01/07/2020 | 0 |
| John | 01/08/2020 | 0 |
| Mike | 01/01/2020 | 4 |
| Mike | 01/02/2020 | 4 |
| Mike | 01/03/2020 | 4 |
| Mike | 01/04/2020 | 3 |
| Mike | 01/05/2020 | 3 |
| Mike | 01/06/2020 | 2 |
| Mike | 01/07/2020 | 2 |
| Mike | 01/08/2020 | 1 |
+------+------------+-----------------------------------------------------------------+
我尝试了很多方法,这是我认为最接近的方法:
SELECT * FROM t1
LEFT OUTER JOIN
(SELECT t1.date, COUNT(DISTINCT phone_number) count, name FROM t1
LEFT OUTER JOIN
t2
ON t1.date < t2.date
GROUP BY t1.date,t2.name
ORDER BY 2 DESC) temp
ON t1.date = temp.date
我仍然从最终结果中丢失行。
这就是我得到的:
+------+------------+-------+
| name | date | count |
+------+------------+-------+
| null | 2020-08-01 | 0 |
| John | 2020-01-01 | 3 |
| John | 2020-02-01 | 3 |
| John | 2020-03-01 | 3 |
| John | 2020-04-01 | 1 |
| John | 2020-05-01 | 1 |
| Mike | 2020-01-01 | 4 |
| Mike | 2020-02-01 | 4 |
| Mike | 2020-03-01 | 3 |
| Mike | 2020-04-01 | 3 |
| Mike | 2020-05-01 | 2 |
| Mike | 2020-06-01 | 2 |
| Mike | 2020-07-01 | 1 |
+------+------------+-------+
使用日历表方法,我们可以构建一个包含所有名称和所有日期的参考表。 然后,将其左连接到包含实际数据的第二个表:
SELECT
b.name,
a.date,
COUNT(DISTINCT t.phone_number) AS unique_numbers
FROM t1 a
CROSS JOIN (SELECT DISTINCT name FROM t2) b
LEFT JOIN t2 t
ON a.date = t.date AND b.name = t.name
GROUP BY
b.name,
a.date
ORDER BY
b.name,
a.date;