【问题标题】:Getting numbers from Last Year获取去年的数字
【发布时间】:2017-03-20 16:34:14
【问题描述】:

我查看了有关 postgreSQL 中时间元素​​的帖子,但到目前为止他们还没有为我点击。我想得到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 数据。

我可以在上面的 sn-ps 中添加什么,它可以为我提供去年至今和去年当月至今的数据。请提供帮助。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    这个怎么样?

    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
    

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

    【讨论】:

      【解决方案2】:

      您的公式很难遵循。您需要针对一个和另一个日期构建结合实际销售日期的查询。所以:

      上一年的开始:

      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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-20
        • 2012-02-13
        • 1970-01-01
        • 2010-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-14
        相关资源
        最近更新 更多