Search code examples
sqlpostgresqlsubquery

How to select data from the last 7 days of Table in Database?


I'm trying to perform a a query in PostgreSQL that be able to display the records from the last 7 days based on the Date field from a table in the Data Base, in my case the field is "fecha_reparto" and the table has the next structure:

drv value fecha_reparto
A 10 22/03/2021
B 2 21/03/2021
C 5 20/03/2021
D 6 15/03/2021
E 7 18/03/2021
F 11 17/03/2021
G 2 16/03/2021
H 1 19/03/2021

And I would like to get something like:

drv value fecha_reparto
A 10 22/03/2021
B 2 21/03/2021
C 5 20/03/2021
H 1 19/03/2021
E 7 18/03/2021
F 11 17/03/2021
G 2 16/03/2021

I tried to use Max() as follow but I got an error:

Select drv, value, MAX(fecha_reparto) from 
reporting_services.vw_mx_log_icaro_descripcion_entregas_comercial
WHERE fecha_reparto >= fecha_reparto - interval '7 days' and drv IS NOT NULL

After that I used the next one query, and I didn't get a error but i'm not pretty sure that it gives me what I want:

select drv,value,MAX(fecha_reparto) as fecha_reparto,
cobertura_3c_promedio from 
reporting_services.vw_mx_log_icaro_descripcion_entregas_comercial
WHERE fecha_reparto >= fecha_reparto - interval '7 days' and drv IS NOT NULL
GROUP BY  drv, value

What do you think guys? It's okay with the last query or would I need something else?

Thanks by the way, best regards.


Solution

  • It appears that you want the 7 day retention period to happen as compared to the most recent date in your table. If so, we can use MAX() here as an analytic function to find this date, then use roughly your first query:

    WITH cte AS (
        SELECT *, MAX(fecha_reparto) OVER() AS max_fecha_reparto
        FROM reporting_services.vw_mx_log_icaro_descripcion_entregas_comercial
    )
    
    SELECT drv, value, fecha_reparto
    FROM cte
    WHERE fecha_reparto >= max_fecha_reparto - INTERVAL '7 days' AND drv IS NOT NULL;