eugene eugene - 7 months ago 29
SQL Question

fetch 5 items for each day in a given month, in raw sql or Django orm

Suppose an event is associated with a date.

For a given month,

I'd like to retrieve events happening in that month,

with a constraint such that:

I want only 5 events at max for each day.


Most databases support the ANSI standard window functions. So, this would be written as:

select t.*
from (select t.*,
             row_number() over (partition by thedate
                                order by thedate) as seqnum
      from t
      where date >= @date1 and date < @date2
     ) t
where seqnum <= 5

@date1 and @date2 are just place holders for the values that define the beginning and end of the period you care about.