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

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

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...