我正在尝试创建一个每月显示月收入的信息中心。我认为最好的方法是创建一个表,每个月都有一行,旁边有收入。目前,一行数据如下所示:
Subscription_ID| Start_Date| End_Date |Monthly_revenue
2384105 | 1/1/2016 | 6/1/2016 |500
我想以某种方式将该行转换为如下所示:
Subscription_ID |Month |Monthly_Revenue
2384105 |1/1/2016 | 500
2384105 |2/1/2016 | 500
2384105 |3/1/2016 | 500
2384105 |4/1/2016 | 500
2384105 |5/1/2016 | 500
2384105 |6/1/2016 | 500
我不知道怎么回事。任何建议都将非常感谢,或者如果你能指出我正确的方向。我正在使用redshift作为我的数据库,所以语法大部分类似于postgres。
编辑:回复评论 - 我可以轻松制作一张包含所有日期和年份的表,如果这有助于参考。
答案 0 :(得分:2)
好的,我查看了一些像这样的redshift文档:
DATEDIFF http://docs.aws.amazon.com/redshift/latest/dg/r_DATEDIFF_function.html
公用表格表达式http://docs.aws.amazon.com/redshift/latest/dg/r_WITH_clause.html
DATEADD http://docs.aws.amazon.com/redshift/latest/dg/r_DATEADD_function.html
//time.bookingTime.iso == 2016-07-20T21:00:00.000Z
{{time.bookingTime.iso | moment}}
这可能对您有用,因为它不使用generate_series()或递归cte。这是postgresSQL版本我尝试使用SQL Fiddle(http://sqlfiddle.com/#!15/f3a23/7/0)....
WITH cteData AS (
SELECT
CAST(2384105 AS INTEGER) AS Subscription_ID
,CAST('2016-01-01' AS DATE) AS Start_Date
,CAST('2016-06-01' AS DATE) AS End_Date
,CAST(500 AS INTEGER) AS Monthly_revenue
)
,cteTally AS (
SELECT 0 AS TallyNum
UNION ALL
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
UNION ALL
SELECT 7
UNION ALL
SELECT 8
UNION ALL
SELECT 9
UNION ALL
SELECT 10
UNION ALL
SELECT 11
)
SELECT
Subscription_ID
,DATEADD(month,c.TallyNum,t.Start_date) AS "Month"
,Monthly_revenue
FROM
cteData t
INNER JOIN cteTally c
ON DATEDIFF(month,t.Start_Date,t.End_Date) >= c.TallyNum