Subtracting 1 day from a timestamp date

后端 未结 1 1120
北海茫月
北海茫月 2021-01-31 13:08

I am using Datagrip for Postgresql. I have a table with a date field in timestamp format (ex: 2016-11-01 00:00:00). I want to be able to:

  1. apply a m
相关标签:
1条回答
  • 2021-01-31 13:27

    Use the INTERVAL type to it. E.g:

    --yesterday
    SELECT NOW() - INTERVAL '1 DAY';
    
    --Unrelated to the question, but PostgreSQL also supports some shortcuts:
    SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
    

    Then you can do the following on your query:

    SELECT 
        org_id,
        count(accounts) AS COUNT,
        ((date_at) - INTERVAL '1 DAY') AS dateat
    FROM 
        sourcetable
    WHERE 
        date_at <= now() - INTERVAL '130 DAYS'
    GROUP BY 
        org_id,
        dateat;
    


    TIPS

    Tip 1

    You can append multiple operands. E.g.: how to get last day of current month?

    SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
    

    Tip 2

    You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

    SELECT make_interval(days => 10 + 2);
    SELECT make_interval(days => 1, hours => 2);
    SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
    


    More info:

    Date/Time Functions and Operators

    datatype-datetime (Especial values).

    0 讨论(0)
提交回复
热议问题