PostgreSQL查询从上周选择数据?

时间:2015-06-11 14:18:41

标签: sql 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' 

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

如何仅从上周获取数据?

2 个答案:

答案 0 :(得分:18)

这种情况将从上周日到周六返回记录:

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

答案 1 :(得分:11)

默认情况下,Postgres会在周日开始几周,所以你很幸运。您可以使用date_trunc()来获取上周的开头:

WHERE (created >= date_trunc('week', CURRENT_TIMESTAMP - interval '1 week') and
       created < date_trunc('week', CURRENT_TIMESTAMP)
      )

编辑:

默认情况下,Postgres会在星期一为 date_trunc 开始一周,但周日为dow。所以,你可以通过尼古拉在他的回答中使用的那种逻辑做你想做的事。