我有一张桌子,里面有我所有的服装。我想选择上周的所有条目(星期从星期天开始)。

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:
使用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

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

10-15 21:31