加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PostgreSQL数据库中取昨天特定时间段的SQL写法

发布时间:2020-12-13 16:37:44 所属栏目:百科 来源:网络整理
导读:highgo=# create table test_bb (c2 timestamp);CREATE TABLEhighgo=# insert into test_bb values (to_timestamp('2018-06-05 19:55:44','yyyy-mm-dd hh24:mi:ss'));INSERT 0 1highgo=# insert into test_bb values (to_timestamp('2018-06-05 03:55:44','y
highgo=# create table test_bb (c2 timestamp);
CREATE TABLE
highgo=# insert into test_bb values (to_timestamp('2018-06-05 19:55:44','yyyy-mm-dd hh24:mi:ss'));
INSERT 0 1
highgo=# insert into test_bb values (to_timestamp('2018-06-05 03:55:44','yyyy-mm-dd hh24:mi:ss'));
INSERT 0 1
highgo=# insert into test_bb values (to_timestamp('2018-06-05 13:55:44','yyyy-mm-dd hh24:mi:ss'));
INSERT 0 1
highgo=# 
highgo=# 
highgo=# select * from test_bb;
         c2          
---------------------
 2018-06-05 19:55:44
 2018-06-05 03:55:44
 2018-06-05 13:55:44
(3 rows)


highgo=# select date_trunc('day',now());
       date_trunc       
------------------------
 2018-06-06 00:00:00+08
(1 row)


highgo=# select date_trunc('day',now()) -interval '1d';
        ?column?        
------------------------
 2018-06-05 00:00:00+08
(1 row)


highgo=# select date_trunc('day',now()) -interval '1d'+interval '6 hours';
        ?column?        
------------------------
 2018-06-05 06:00:00+08
(1 row)


highgo=# select date_trunc('day',now())-interval '6 hours';
        ?column?        
------------------------
 2018-06-05 18:00:00+08
(1 row)


highgo=# select * from test_bb
highgo-#  where (c2 > date_trunc('day',now()) - interval '1 day' and c2 < date_trunc('day',now()) - interval '1d' + interval '6 hours')
highgo-#     or (c2 > date_trunc('day',now()) - interval '6 hours' and c2 < date_trunc('day',now()));
         c2          
---------------------
 2018-06-05 19:55:44
 2018-06-05 03:55:44
(2 rows)


highgo=# select * from test_bb;
         c2          
---------------------
 2018-06-05 19:55:44
 2018-06-05 03:55:44
 2018-06-05 13:55:44
(3 rows)

如上的这个where条件就是取昨天特定时间段的SQL写法。

参考:https://www.postgresql.org/docs/10/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读