【问题标题】:Summing Moving Range and Criteria, Grouping by Day汇总移动范围和标准,按天分组
【发布时间】:2017-09-22 17:24:48
【问题描述】:

我要做的是根据标准和按天分组过去 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

即使使用“当前日期 - 间隔 -30 天”也只是查找..当前日期。

使用 Postgres 8.0.2

【问题讨论】:

  • 您可以使用sqlfiddle.com 制作示例架构并将其链接到您的原始问题中吗?
  • 使用group by date(cast(f.hire_date__c as date)),rr.Cancels, qq.hires

标签: sql postgresql


【解决方案1】:

使用 group by 如下。您在列选择中将日期时间转换为日期,但不是在分组中

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 2016-03-31
    • 2015-04-26
    • 2015-03-31
    • 1970-01-01
    相关资源
    最近更新 更多