在snowflake中将每月数据分解为每日数据

de90aj5v  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(303)

这个问题与这里的问题类似:将每月数据分解为每日数据
但是,我正在尝试使用snowflake来实现这一点。以下是一些示例数据:

+--------------------+----------+---------------------------+----------+---------------+--------+
|         ID         | METRIC_C | OPPORTUNITY_RECORD_TYPE_C | REGION_C | METRIC_DATE_C | GOAL_C |
+--------------------+----------+---------------------------+----------+---------------+--------+
| a0c0W00000P180rQAB | MQL      | Buyer: New                | Europe   | 2020-11-01    |    227 |
| a0c0W00000P181UQAR | Won      | Buyer: New                  Europe   | 2020-02-01    |      1 |
| a0c0W00000P180yQAB | SAL      | Buyer: New                | Europe   | 2020-06-01    |     34 |
+--------------------+----------+---------------------------+----------+---------------+--------+

基本上,我希望id、metric、opportunity、record、type、region的值是重复的,并且整个月都有date值。目标值应除以当月天数。我似乎无法让代码在雪花中工作。以下是我目前掌握的情况:

with cte as
(select ID, METRIC_C, OPPORTUNITY_RECORD_TYPE_C, REGION_C, METRIC_DATE_C, GOAL_C
 from GOAL_C
 where METRIC_DATE_C > '2019-12-31'
 union all
 select ID, METRIC_C, OPPORTUNITY_RECORD_TYPE_C, REGION_C, dateadd(d, 1, METRIC_DATE_C) METRIC_DATE_C, GOAL_C
 from cte
 where datediff(m,METRIC_DATE_C,dateadd(d, 1, METRIC_DATE_C))=0
 and METRIC_DATE_C > '2019-12-31'
)
select ID, METRIC_C, OPPORTUNITY_RECORD_TYPE_C, REGION_C, METRIC_DATE_C, 
       1.0*GOAL_C / count(*) over (partition by ID, METRIC_C, OPPORTUNITY_RECORD_TYPE_C, REGION_C, METRIC_DATE_C) GOAL_C
from cte
order by 1,2,3,4,5

代码似乎并没有把一个月分成几天。任何帮助都将不胜感激!

sczxawaw

sczxawaw1#

你的代码很好,只是对snowflake语法做了一点小小的调整。干得好:

with cte as
(select ID, METRIC_C, OPPORTUNITY_RECORD_TYPE_C, REGION_C, METRIC_DATE_C, GOAL_C
 from DB_NM.SCHEMA_NM.TABLE_NM
 where METRIC_DATE_C > '2019-12-31'
 union all
 select ID, METRIC_C, OPPORTUNITY_RECORD_TYPE_C, REGION_C, dateadd(day, 1, METRIC_DATE_C) METRIC_DATE_C, GOAL_C
 from cte
 where datediff(month,METRIC_DATE_C,dateadd(day, 1, METRIC_DATE_C))=0
 and METRIC_DATE_C > '2019-12-31'
)
select ID, METRIC_C, OPPORTUNITY_RECORD_TYPE_C, REGION_C, METRIC_DATE_C, 
       1.0*GOAL_C / count(*) over (partition by ID, METRIC_C, OPPORTUNITY_RECORD_TYPE_C, REGION_C, METRIC_DATE_C) GOAL_C
from cte
order by 1,2,3,4,5
;

谢谢

相关问题