SQL / Vertica - 在日历上加入包含开始日期和结束日期的事件

时间:2016-03-15 15:23:33

标签: sql timeline vertica

简而言之

我有几个促销活动的开始日期和结束日期,我想加入日历,看看促销活动在哪些日期。

我目前拥有什么

表1

PromoName  BeginDate   EndDate     PromoType    
Promo1     2016-03-10  2016-03-12  Type1
Promo2     2016-03-11  2016-03-12  Type2
Promo3     2016-03-14  2016-03-15  Type1

表2

Date   
2016-03-09
2016-03-10
2016-03-11
2016-03-12
2016-03-13
etc

我想拥有什么

Date        PromoActive  PromoType1Active  PromoType2Active
2016-03-09  0            0                 0
2016-03-10  1            1                 0
2016-03-11  1            1                 1
2016-03-12  1            1                 1
2016-03-13  0            0                 0
2016-03-14  1            1                 0
2016-03-06  1            1                 0

1 个答案:

答案 0 :(得分:0)

这很简单。无需使用Vertica的高级时间序列分析功能...

假设你有:

SQL> select * from table1;
 promoname | begindate  |  enddate   | promotype 
-----------+------------+------------+-----------
 Promo1    | 2016-03-10 | 2016-03-12 | Type1
 Promo3    | 2016-03-14 | 2016-03-15 | Type1
 Promo2    | 2016-03-11 | 2016-03-12 | Type2

SQL> select * from table2 order by sdate;
   sdate    
------------
 2016-03-09
 2016-03-10
 2016-03-11
 2016-03-12
 2016-03-13
 2016-03-14
 2016-03-15
 2016-03-16

然后,这样一个简单的SQL应该可以工作:

select 
    sdate, 
    max(case when ( sdate between begindate and enddate ) then 1 else 0 end) as PromoActive,                                                                         
    max(case when ( sdate between begindate and enddate ) and promotype = 'Type1' then 1 else 0 end) as PromoType1Active, 
    max(case when ( sdate between begindate and enddate ) and promotype = 'Type2' then 1 else 0 end) as PromoType2Active
from 
    table1 cross join table2 
group by sdate
order by sdate
;
   sdate    | PromoActive | PromoType1Active | PromoType2Active 
------------+-------------+------------------+------------------
 2016-03-09 |           0 |                0 |                0
 2016-03-10 |           1 |                1 |                0
 2016-03-11 |           1 |                1 |                1
 2016-03-12 |           1 |                1 |                1
 2016-03-13 |           0 |                0 |                0
 2016-03-14 |           1 |                1 |                0
 2016-03-15 |           1 |                1 |                0
 2016-03-16 |           0 |                0 |                0