使用current_date获取过去12个月的月初和月末

时间:2020-04-02 08:21:36

标签: postgresql performance date group-by summary

我正在编写以下查询以按月计算销售率,并且我想确保它始终查看间隔:过去12个月的月初至月底。我已经尝试了以下方法,但是我不确定它是否需要使用本月的第一天和最后一天,我觉得可以用较短的查询来编写?

select 
datetrunc('month',date)
,count(id) filter (where status='sold' and (date between (datetrunc('month','current_date - interval '1 months')) and datetrunc('month', current_date) - Interval '1 days'))
/ count(id) filter (where date between (datetrunc('month','current_date - interval '1 months')) and datetrunc('month', current_date) - Interval '1 days') as Mar2020_Sales_Rate
,..... as Feb2020_Sales_Rate
,.
,.
,..... as Mar2019_Sales_Rate
from sales
group by 1;

1 个答案:

答案 0 :(得分:0)

这是我选择获取月1日和月底的方式,而不使用当前日期,而是使用数据中的(订单的)创建日期。请提出其他似乎更有效的查询,或者如果您认为此查询存在缺陷,请提出建议:

select distinct creation_date::date,
       (creation_date - Interval '1 months')::date as Minus_1M,
       (creation_date - Interval '2 months')::date as Minus_2M,
       (creation_date - Interval '3 months')::date as Minus_3M,
       ...
       (creation_date - Interval '12 months')::date as Minus_12M,
       extract('day' from creation_date) as Day_of_month,
       date_trunc('month', (creation_date::date - extract('day' from 
       creation_date)::int))::date as Beginning_of_month,
       creation_date::date - extract('day' from creation_date)::int as End_of_month
from order_data
order by 1 desc;