总结移动范围和标准,按日分组

时间:2017-09-22 17:24:48

标签: sql postgresql

我要做的是根据标准和小组计算最近30天的日期,代码的一天如下:

select
sum(case when f.hire_date__c between '2017-08-01 00:00:00' and '2017-09-01 
00:00:00' 
and t.createddate  between '2017-08-01 00:00:00' and '2017-09-01 00:00:00'
and t.name = 'Request' then 1 else 0 end) as Requests
            from case_task_c as t
            join case_file_c as f
            on f.id = t.case_file__c

我可以根据今天的日期等相应地调整30天回顾的日期。我无法弄清楚的是每天都有这个查询组,即昨天的结果,前一天等等对于调整后的日期范围。

到目前为止,我有这个:

select 
date(cast(f.hire_date__c as date)),
row_number() over (order by f.hire_date__c desc) as rownumber,
rr.Cancels as Cancels,
qq.hires as hires,
sum(rr.Cancels) over (rows between 1 following and 30 following) as 
CumulCancel,
sum(qq.Hires) over (rows between 1 following and 30 following) as Hires
from case_file_c as f
    left join(
            select
            cast(f.hire_date__c as date) as date1,
            sum(case when 
            t.name = 'Cancellation Request' then 1 else 0 end) as Cancels
            from case_task_c as t
            join case_file_c as f
            on f.id = t.case_file__c
            group by date1)
            as rr
            on rr.date1 = cast(f.hire_date__c as date)
    left join(
            select
            cast(f.hire_date__c as date) as date2,
            sum(case when f.hire_date__c is not null then 1 else 0 end) as 
            hires
            from sf_case_file_c as f
            group by date2) as qq
            on qq.date2 = cast(f.hire_date__c as date)
where f.hire_date__c is not null 
and f.hire_date__c >= '2017-01-01 00:00:00'
and f.hire_date__c between date_add('day',-30,current_date) and current_date
group by f.hire_date__c, rr.Cancels, qq.hires
order by f.hire_date__c desc

即使使用'current_date - interval -30 day'也只是查找当前日期。

使用Postgres 8.0.2

1 个答案:

答案 0 :(得分:0)

按照以下方式使用组。您正在将列日期中的日期时间转换为日期,但不是按

分组
GROUP BY date(cast(f.hire_date__c as date)),rr.Cancels, qq.hires