Ниже для BigQuery Standard SQL
#standardSQL
SELECT time_stamp, COALESCE(`count`, 0) `count`
FROM (
SELECT DISTINCT time_stamp FROM `project.dataset.table_1`
) LEFT JOIN (
SELECT time_stamp, COUNT(id) AS `count`
FROM (
SELECT t1.id, t1.time_stamp, ARRAY_AGG(t2.time_stamp) matches
FROM `project.dataset.table_1` t1
JOIN `project.dataset.table_2` t2
ON t1.id = t2.id
GROUP BY id, time_stamp
)
WHERE EXISTS (
SELECT 1
FROM UNNEST(matches) match
WHERE PARSE_DATE('%Y-%m', match)
BETWEEN PARSE_DATE('%Y-%m', time_stamp)
AND DATE_ADD(PARSE_DATE('%Y-%m', time_stamp), INTERVAL 2 MONTH)
)
GROUP BY time_stamp
) USING (time_stamp)
Вы можете протестировать, поиграть с приведенными выше примерами данных, как есть в вашем вопросе
#standardSQL
WITH `project.dataset.table_1` AS (
SELECT '2019-06' time_stamp, 1 id UNION ALL
SELECT '2019-06', 2 UNION ALL
SELECT '2019-06', 3 UNION ALL
SELECT '2019-07', 4 UNION ALL
SELECT '2019-07', 5 UNION ALL
SELECT '2019-08', 6 UNION ALL
SELECT '2019-08', 7 UNION ALL
SELECT '2019-09', 8 UNION ALL
SELECT '2019-09', 9 UNION ALL
SELECT '2019-10', 10
), `project.dataset.table_2` AS (
SELECT '2019-06' time_stamp, 1 id UNION ALL
SELECT '2019-06', 13 UNION ALL
SELECT '2019-06', 8 UNION ALL
SELECT '2019-07', 2 UNION ALL
SELECT '2019-07', 9 UNION ALL
SELECT '2019-08', 12 UNION ALL
SELECT '2019-08', 4 UNION ALL
SELECT '2019-09', 5 UNION ALL
SELECT '2019-09', 13 UNION ALL
SELECT '2019-10', 11 UNION ALL
SELECT '2019-10', 6 UNION ALL
SELECT '2019-10', 3
)
SELECT time_stamp, COALESCE(`count`, 0) `count`
FROM (
SELECT DISTINCT time_stamp FROM `project.dataset.table_1`
) LEFT JOIN (
SELECT time_stamp, COUNT(id) AS `count`
FROM (
SELECT t1.id, t1.time_stamp, ARRAY_AGG(t2.time_stamp) matches
FROM `project.dataset.table_1` t1
JOIN `project.dataset.table_2` t2
ON t1.id = t2.id
GROUP BY id, time_stamp
)
WHERE EXISTS (
SELECT 1
FROM UNNEST(matches) match
WHERE PARSE_DATE('%Y-%m', match)
BETWEEN PARSE_DATE('%Y-%m', time_stamp)
AND DATE_ADD(PARSE_DATE('%Y-%m', time_stamp), INTERVAL 2 MONTH)
)
GROUP BY time_stamp
) USING (time_stamp)
с результатом
Row time_stamp count
1 2019-06 2
2 2019-07 2
3 2019-08 1
4 2019-09 0
5 2019-10 0