gpt4 book ai didi

sql - PostgreSQL 查询选择上周的数据?

转载 作者:行者123 更新时间:2023-11-29 11:12:50 24 4
gpt4 key购买 nike

我有一张表,上面有我的顾客的所有购买。我想选择上周的所有条目(一周从星期日开始)。

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

对@d456 的回答:

Wouldn't using BETWEEN include midnight on Sunday at both ends of the interval?

没错,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

关于sql - PostgreSQL 查询选择上周的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30783452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com