user1572215 user1572215 - 5 months ago 14
SQL Question

postgres last 10 working days

I would like to select rows which are within last 10 working days. Working days are assumed to be dates when rows are present.

Thanks in advance.

Answer

You can simply take the last ten days, using something like this:

select t.*
from table t
where t.date in (select t2.date
                 from table t2
                 group by t2.date
                 order by t2.date desc
                 limit 10
                );

An alternative is to use the dense_rank() function:

select t.*
from (select t.*, dense_rank() over (order by date desc) as seqnum
      from table t
     ) t
where seqnum <= 10;

Both of these assume that the date column has no time component. Removing the time component is a trivial adjustment to either version.

Comments