PostgreSQL查询以选择上周的数据?

我有一张桌子,上面有我所有顾客购买的东西。我想选择上周(从周日开始的一周)中的所有条目。

id    value  date

5907 1.20 "2015-06-05 09:08:34-03"

5908 120.00 "2015-06-09 07:58:12-03"

我已经试过了:

SELECT id, valor, created, FROM compras WHERE created >= now() - interval '1 week' and parceiro_id= '1'

但是我得到了上周的数据,包括本周的数据,我只想要上周的数据。

如何只获取上周的数据?

回答:

此条件将返回上周日至周六的记录:

WHERE created BETWEEN

NOW()::DATE-EXTRACT(DOW FROM NOW())::INTEGER-7

AND NOW()::DATE-EXTRACT(DOW from NOW())::INTEGER

有一个例子:

WITH compras AS (

SELECT ( NOW() + (s::TEXT || ' day')::INTERVAL )::TIMESTAMP(0) AS created

FROM generate_series(-20, 20, 1) AS s

)

SELECT to_char( created, 'DY'::TEXT), created

FROM compras

WHERE created BETWEEN

NOW()::DATE-EXTRACT(DOW FROM NOW())::INTEGER-7

AND NOW()::DATE-EXTRACT(DOW from NOW())::INTEGER

BETWEEN在间隔的两端不使用星期日的午夜吗?

没错,BETWEEN包括间隔两端的周日午夜。要在间隔结束时排除周日的午夜,必须使用运算符>=<

WITH compras AS (

SELECT s as created

FROM generate_series( -- this would produce timestamps with 20 minutes step

(now() - '20 days'::interval)::date,

(now() + '20 days'::interval)::date,

'20 minutes'::interval) AS s

)

SELECT to_char( created, 'DY'::TEXT), created

FROM compras

WHERE TRUE

AND created >= NOW()::DATE-EXTRACT(DOW FROM NOW())::INTEGER-7

AND created < NOW()::DATE-EXTRACT(DOW from NOW())::INTEGER

以上是 PostgreSQL查询以选择上周的数据? 的全部内容, 来源链接: utcz.com/qa/409031.html

回到顶部