2017-03-22 27 views
0

因此,我正在为客户进行群组分析,其中群组是同一月份开始使用该产品的一组人员。然后,我会跟踪每个后续月份到目前为止每个队列的总体使用情况。例如,第一个“队列月”是2012年1月,然后我有“使用月份”1月12日,2月12日,3月12日,......,3月17日(本月)。一列是“队列月”,另一列是“使用月”。这个过程重复每个后续的队列月份。该表是这样的:将未来日期的集合列表添加到SQL查询中的行

Jan 12 | Jan 12 
Jan 12 | Feb 12 
... 
Jan 12 | Mar 17 
Feb 12 | Feb 12 
Feb 12 | Mar 12 
... 
Feb 12 | Mar 17 
... 
Feb 17 | Feb 17 
Feb 17 | Mar 17 
Mar 17 | Mar 17 

问题就出现了,因为我想为一年做出来的预测现有和未来的同伙。 这意味着对于1月12日的队列,我想要做4月17日到3月18日的预测。 我也想从4月17日到3月18日对4月17日队列(现在还不存在)进行预测。直到3月18日的3月18日队列预测。 我可以处理预测,不用担心。

我的问题是,我无法弄清楚如何在每个群组切换之前的“使用月份”列中添加此列表(4月17日。3月17日)。 我还需要在4月17日至3月18日加入队列,并对这些未来队列中的每个队列(4月17日... 3月17日)列出适用部分。

所以我想表的样子:

Jan 12 | Jan 12 
Jan 12 | Feb 12 
... 
Jan 12 | Mar 17 
Jan 12 | Apr 17 
..  
Jan 12 | Mar 18 
Feb 12 | Feb 12 
Feb 12 | Mar 12 
... 
Feb 12 | Mar 17 
Feb 12 | Apr 17 
... 
Feb 12 | Mar 18 
...  
...  
Feb 17 | Feb 17 
Feb 17 | Mar 17  
... 
Feb 17 | Mar 18 
Mar 17 | Mar 17  
... 
Mar 17 | Mar 18 

我知道第一个来解决心中做一个创建一个列表的所有日期1月12日至3月18日,交其加入到自己,然后将外部连接留给当前的表格(队列/使用月份范围从1月12日到3月17日)。但是,这不可扩展。

有没有一种方法可以迭代添加到明年的月份列表中?在绝对必要

我使用HP Vertica的,可以使用Presto或蜂巢

回答

0

我认为你应该使用的查询这里下面创建一个临时表无中生有,并与您的查询的其余部分加入。恐怕,你不能以SQL的程序方式做任何事情。没有CROSS JOIN,你将无法离开。但是,在这里,您将CROSS JOIN限制为您需要的第一对月份对的生成。

这里所说:

WITH 
-- create a list of integers from 0 to 100 using the TIMESERIES clause 
i(i) AS (
SELECT dt::DATE - '2000-01-01'::DATE 
FROM ( 
      SELECT '2000-01-01'::DATE + 0 
UNION ALL SELECT '2000-01-01'::DATE + 100 
) d(d) 
TIMESERIES dt AS '1 day' OVER(ORDER BY d::TIMESTAMP) 
) 
, 
-- limits are Jan-2012 to the first of the current month plus one year 
month_limits(month_limit) AS (
      SELECT '2012-01-01'::DATE 
UNION ALL SELECT ADD_MONTHS(TRUNC(CURRENT_DATE,'MONTH'),12) 
) 
-- create the list of possible months as a CROSS JOIN of the i table 
-- containing the integers and the month_limits table, using ADD_MONTHS() 
-- and the smallest and greatest month of the month limits 
,month_list AS (
SELECT 
    ADD_MONTHS(MIN(month_limit),i) AS month_first 
FROM month_limits CROSS JOIN i 
GROUP BY i 
HAVING ADD_MONTHS(MIN(month_limit),i) <= (
    SELECT MAX(month_limit) FROM month_limits 
) 
) 
-- finally, CROSS JOIN the obtained month list with itself with the 
-- filters needed. 
SELECT 
    cohort.month_first AS cohort_month 
, use.month_first AS use_month 
FROM month_list AS cohort 
CROSS JOIN month_list AS use 
WHERE use.month_first >= cohort.month_first 
ORDER BY 1,2 
; 
相关问题