在开始日期和结束日期内生成所有季度

时间:2017-06-09 00:22:00

标签: sql amazon-redshift

我有一张包含不同广告系列的表格。每个广告系列都有一个开始日期和结束日期。

campaign id | start date | end date |

我想知道这些活动在哪些季度发生。

理想情况下它会是这样的 - 在这些四分之一列下,它会显示一个0和1的二进制变量。

account id | campaign id | start date | end date | 2015q1 | 2015q2 | 2015q3 |...etc

例如,如果广告系列在2015年1月1日 - 2015年5月2日期间发生,则结果为:

| 2015q1 | 2015q2 | 2015q3 |
| 1      | 1      | 0      |

我正在使用Amazon Redshift。

2 个答案:

答案 0 :(得分:0)

将结果放入列时,必须对值进行硬编码。例如,此输入数据:

SELECT
  id,
  start_date,
  end_date,
  (CASE WHEN start_date < '2016-04-01' AND end_date >= '2016-01-01' THEN 1 ELSE 0 END) as Q1_2016,
  (CASE WHEN start_date < '2016-07-01' AND end_date >= '2016-04-01' THEN 1 ELSE 0 END) as Q2_2016,
  (CASE WHEN start_date < '2016-10-01' AND end_date >= '2016-07-01' THEN 1 ELSE 0 END) as Q3_2016,
  (CASE WHEN start_date < '2017-01-01' AND end_date >= '2016-10-01' THEN 1 ELSE 0 END) as Q4_2016
FROM campaign

使用此查询:

1   2016-03-23  2016-07-18  1   1   1   0
2   2016-01-01  2016-01-02  1   0   0   0
3   2016-10-05  2016-11-05  0   0   0   1
4   2016-01-01  2016-12-31  1   1   1   1

给出了这个结果:

val rdd1 = sc.makeRDD(20 to 100)
  .filter(_ % 8 == 0).map(Math.sqrt(_)).map(e1 => (e1.toInt, e1)).cache()
rdd1.collect

不幸的是,没有可以为你自动创建列的SQL技巧。

答案 1 :(得分:0)

您可以使用提取(从日期开始的季度)功能,如下所示:

SELECT
   campaign_id,
   case when start_quarter=1 and start_year=2015 then 1 else 0 end as q1_2015,
   case when start_quarter=2 and start_year=2015 then 1 else 0 end as q2_2015,
   case when start_quarter=3 and start_year=2015 then 1 else 0 end as q3_2015,
   case when start_quarter=4 and start_year=2015 then 1 else 0 end as q4_2015
FROM (
  SELECT
    campaign_id,
    extract(MONTH FROM start_date) AS start_month,
    extract(YEAR FROM start_date)  AS start_year,
    extract(QUARTER from start_date) as start_quarter,
    extract(MONTH FROM end_date)   AS end_month,
    extract(YEAR FROM end_date)    AS end_year,
    extract(QUARTER FROM end_date) AS end_quarter
  FROM table
) t1

或者如果您更喜欢没有硬编码的选项,您可以简单地使用子查询。

SELECT
    campaign_id,
    extract(MONTH FROM start_date) AS start_month,
    extract(YEAR FROM start_date)  AS start_year,
    extract(QUARTER from start_date) as start_quarter,
    extract(MONTH FROM end_date)   AS end_month,
    extract(YEAR FROM end_date)    AS end_year,
    extract(QUARTER FROM end_date) AS end_quarter
  FROM table

此选项将为您提供如下结果:

campaing_id start month start year  start quarter   end month   end year    end quarter
    4   2015    2   4   2015    2
    3   2017    1   3   2017    1
    2   2015    1   3   2015    1
    12  2014    4   12  2014    4
    2   2017    1   2   2017    1
    7   2016    3   8   2016    3