我看过postgreSQL中关于time元素的帖子,但到目前为止还没有为我点击。我想得到Last Year to Date,在这个案例中,01/01/2016至03/20/2016和Last Year Month to Date,在本例中03/01/2016至03/20/2016。
Get last 12 months data from Db with year in Postgres
get last three month records from table
select actual_sale_date from allsalesdata
where actual_sale_date > date_trunc('year', current_date)提供2017年至今的年度
select actual_sale_date from allsalesdata
where actual_sale_date > date_trunc('month', current_date)提供2017年迄今的月份
select actual_sale_date from allsalesdata
where actual_sale_date >= date_trunc('year', now() - interval '1 year')
and actual_sale_date < date_trunc('year',now())提供去年01/01 -> 12/31的数据。
我可以添加到上面的片段,这将为我提供去年至今和上个月至今的数据。请提供协助。
发布于 2017-03-20 16:41:19
这个怎么样?
select actual_sale_date
from allsalesdata
where actual_sale_date + interval '1' year >= date_trunc('year', current_date) and
actual_sale_date + interval '1' year < current_date也就是说,在去年的日期上加上一年,并与今年进行比较。我建议增加一年,并使用今年的日期。更直观地处理闰年(在我看来)。
发布于 2017-03-20 16:42:23
你的公式很难遵循。您需要将actual_sale_date与一个日期和另一个日期结合起来构造查询。因此:
前一年年初:
t=# select date_trunc('year', now() - interval '1 year');
date_trunc
------------------------
2016-01-01 00:00:00+00
(1 row)今天开始:
t=# select date_trunc('day', now());
date_trunc
------------------------
2017-03-20 00:00:00+00
(1 row)前一年当月初:
t=# select date_trunc('month', (now() - interval '1 year'));
date_trunc
------------------------
2016-03-01 00:00:00+00
(1 row)因此,如果“上个月迄今的数据”意味着从2016年开始,3月1日到现在:
select actual_sale_date from allsalesdata
where actual_sale_date >= date_trunc('month', (now() - interval '1 year'))
and actual_sale_date <= now()https://stackoverflow.com/questions/42909064
复制相似问题