如何以非冗余方式显示不同时间段的数据?

时间:2017-11-06 21:48:03

标签: postgresql

我正在进行一个查询,我在每个时间段都在呈现数据查询已经变得多余,而且变得如此困难,因为我有更多的类别。

查询

select 'MISC' as Label, 'MISC 12 months' as Label, min(created_at), count(*) FROM services

1 个答案:

答案 0 :(得分:0)

请运行此小型查询,因为它可以帮助您理解要遵循的建议。基本上它只是一个间隔列表,然后我们可以使用它来创建一组日期。

WITH Ranges as (
     select '1 day' as duration union all
     select '1 month' as duration union all
     select '1 week' as duration union all
     select '2 months' as duration union all
     select '3 months' as duration union all
     select '4 months' as duration union all
     select '5 months' as duration union all
     select '6 months' as duration union all
     select '12 months' as duration
    )
select current_date - r.duration::interval
from ranges r
;

因此,我们通过服务表上的CROSS JOIN使用该间隔表作为标签和间隔(因此我们为每个间隔获得一个服务行),然后我们使用“条件聚合” (聚合函数内的case表达式)来获得想要的结果。您可以在公用表表达式中添加或删除新的时间间隔,或者(可选)如果您需要在许多查询中使用这些时间表,则可以创建实际表。

WITH Ranges as (
     select '1 day' as duration union all
     select '1 month' as duration union all
     select '1 week' as duration union all
     select '2 months' as duration union all
     select '3 months' as duration union all
     select '4 months' as duration union all
     select '5 months' as duration union all
     select '6 months' as duration union all
     select '12 months' as duration
    )
select
    , concat('MISC ',r.duration) as Label
    , current_date - r.duration::interval as dt_from
    , min(case when created_at > current_date - r.duration::interval then created_at end) as min_created_at
    , count(case when created_at > current_date - r.duration::interval then created_at end) as count_of
from services
cross JOIN Ranges r
group by
      r.duration

我没有机会测试较低的查询,请原谅其中的任何错误。