简体   繁体   English

知道如何从今天的日期检索属于前一周的日期吗?

[英]Any idea how can i retrieve dates that belong to the week before from today's date?

I have a table "dates" with ids and dates: (the dates are in timestamp)我有一个带有 ID 和日期的表格“日期”:(日期在时间戳中)

id start_date
1  2020-11-23 11:00:00
2  2020-11-23 12:00:00
3  2020-11-15 10:00:00
4  2020-11-24 09:00:00
5  2020-11-11 09:00:00
6  2020-11-24 13:00:00
7  2020-11-25 15:00:00

the code should return ids:代码应返回 ID:

id
 1
 2
 4
 6
 7

i tried the following:我尝试了以下方法:

select id
from dates
where dates.start_date > DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())+6 DAY) 
AND dates.start_date <= DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())-1 DAY)

but it didn't seem to work.但它似乎没有用。 I'm having a syntax error:我有一个语法错误:

ERROR: syntax error at or near "DAYOFWEEK"错误:“DAYOFWEEK”或附近的语法错误

Consider today's date: 2020-11-26 I'm also using PostgreSQL!考虑今天的日期:2020-11-26 我也在使用 PostgreSQL!

You seem to want:你似乎想要:

select id
from t
where t.start_date > current_date - interval '7 day';

Or, perhaps -- depending on how you define "week":或者,也许——取决于你如何定义“周”:

where t.start_date >= date_trunc('week', current_date) - interval '7 day' and
      t.start_date < date_trunc('week', current_date)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM