PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Query PostgreSQL per selezionare i dati della scorsa settimana?

Questa condizione restituirà i record da domenica a sabato della scorsa settimana:

WHERE created BETWEEN
    NOW()::DATE-EXTRACT(DOW FROM NOW())::INTEGER-7 
    AND NOW()::DATE-EXTRACT(DOW from NOW())::INTEGER

C'è un esempio:

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

In risposta a @d456:

Proprio così, BETWEEN include la mezzanotte di domenica ad entrambe le estremità dell'intervallo. Per escludere la mezzanotte di domenica a fine intervallo è necessario utilizzare gli operatori >= e < :

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