本文介绍了PostgreSQL查询以选择上周的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a table which has all the purchases of my costumers. I want to select all entries from the last week, (week start from Sunday).

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'

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

But I got the data from the last week including data from this week, I only want data from the last week.

如何仅从上周获得数据?

How to get data only from last week ?

推荐答案

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

This condition will return records from Sunday till Saturday last week:

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 包括午夜在间隔的两端的星期日。要在间隔结束时排除周日的午夜,必须使用运算符> = <

That right, BETWEEN includes midnight on Sunday at both ends of the interval. To exclude midnight on Sunday at end of interval it is necessary to use operators >= and <:

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查询以选择上周的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 06:06