首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >去年的数字

去年的数字
EN

Stack Overflow用户
提问于 2017-03-20 16:34:14
回答 2查看 1.7K关注 0票数 1

我看过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

代码语言:javascript
复制
select actual_sale_date from allsalesdata
where actual_sale_date > date_trunc('year', current_date)

提供2017年至今的年度

代码语言:javascript
复制
select actual_sale_date from allsalesdata
where actual_sale_date > date_trunc('month', current_date)

提供2017年迄今的月份

代码语言:javascript
复制
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的数据。

我可以添加到上面的片段,这将为我提供去年至今和上个月至今的数据。请提供协助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-20 16:41:19

这个怎么样?

代码语言:javascript
复制
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

也就是说,在去年的日期上加上一年,并与今年进行比较。我建议增加一年,并使用今年的日期。更直观地处理闰年(在我看来)。

票数 2
EN

Stack Overflow用户

发布于 2017-03-20 16:42:23

你的公式很难遵循。您需要将actual_sale_date与一个日期和另一个日期结合起来构造查询。因此:

前一年年初:

代码语言:javascript
复制
t=# select date_trunc('year', now() - interval '1 year');
       date_trunc
------------------------
 2016-01-01 00:00:00+00
(1 row)

今天开始:

代码语言:javascript
复制
t=# select date_trunc('day', now());
       date_trunc
------------------------
 2017-03-20 00:00:00+00
(1 row)

前一年当月初:

代码语言:javascript
复制
t=# select date_trunc('month', (now() - interval '1 year'));
       date_trunc
------------------------
 2016-03-01 00:00:00+00
(1 row)

因此,如果“上个月迄今的数据”意味着从2016年开始,3月1日到现在:

代码语言:javascript
复制
select actual_sale_date from allsalesdata
where actual_sale_date >= date_trunc('month', (now() - interval '1 year'))       
and actual_sale_date <= now()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42909064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档