我有一个表,其中包含以下字段:customer_id
,start_trial_date
,end_trial_date
。我正在尝试编写一个查询,可以用来计算给定日期的customer_id
。
|+-------------+------------+------------+
| customer_id | start_date | end_date |
+-------------+------------+------------+
| 1 | 2017-02-03 | 2017-05-01 |
| 2 | 2017-04-07 | 2017-09-01 |
| 3 | 2017-03-02 | 2018-03-04 |
| 4 | 2013-02-25 | 2015-01-22 |
| 5 | 2015-11-10 | 2016-03-25 |
| .... | .... | .... |
+-------------+------------+------------+
我将如何编写查询以生成一个结果集,该结果集的所有日期都在一个计数范围内,其中customer_id
的有效期限包括该日期?
预期输出:
+------------+-----------+
| date | customers |
+------------+-----------+
| 2013-01-01 | 0 |
| …. | …. |
| 2017-04-20 | 3 |
| ….. | …. |
| 2018-12-31 | …. |
+------------+-----------+
如果这很重要,我正在使用BigQuery。我曾考虑过创建一个助手表,该表列出一个范围的所有日期,然后尝试将其加入到我的表中并进行计数,但是在这种方法中我没有很好的联接键。
答案 0 :(得分:1)
创建日历表是一个很好的起点。一旦有了该表(例如表calendar
的列为calendar_date
),就可以使用LEFT JOIN
和聚合了:
SELECT c.calendar_date, COUNT(t.customer_id) customers
FROM calendar c
LEFT JOIN mytable t
ON c.calendar_date >= t.start_date AND c.calendar_date <= t.end_date
GROUP BY c.calendar_date
注意:您可能需要根据您的确切要求调整不平等条件(>=
或>
,<=
或<
)。
答案 1 :(得分:1)
以下是用于BigQuery标准SQL
#standardSQL
WITH calendar AS (
SELECT day
FROM (
SELECT MIN(start_date) min_date, MAX(end_date) max_date
FROM `project.dataset.table`
), UNNEST(GENERATE_DATE_ARRAY(min_date, max_date)) day
)
SELECT day, COUNTIF(day BETWEEN start_date AND end_date) customers
FROM calendar, `project.dataset.table`
GROUP BY day
您可以使用下面的示例中的虚拟数据来测试,玩游戏
#standardSQL
WITH `project.dataset.table` AS (
SELECT 1 customer_id, DATE '2017-01-01' start_date, DATE '2017-01-05' end_date UNION ALL
SELECT 2, '2017-01-03', '2017-01-04' UNION ALL
SELECT 3, '2017-01-04', '2017-01-06' UNION ALL
SELECT 4, '2017-01-10', '2017-01-12' UNION ALL
SELECT 5, '2017-01-12', '2017-01-13'
), calendar AS (
SELECT day
FROM (
SELECT MIN(start_date) min_date, MAX(end_date) max_date
FROM `project.dataset.table`
), UNNEST(GENERATE_DATE_ARRAY(min_date, max_date)) day
)
SELECT day, COUNTIF(day BETWEEN start_date AND end_date) customers
FROM calendar, `project.dataset.table`
GROUP BY day
-- ORDER BY day
有结果
Row day customers
1 2017-01-01 1
2 2017-01-02 1
3 2017-01-03 2
4 2017-01-04 3
5 2017-01-05 2
6 2017-01-06 1
7 2017-01-07 0
8 2017-01-08 0
9 2017-01-09 0
10 2017-01-10 1
11 2017-01-11 1
12 2017-01-12 2
13 2017-01-13 1