Search code examples
sqlpostgresqlmin

sql to find row for min date in each month


I have a table, lets say "Records" with structure:

id      date
--      ----
1       2012-08-30
2       2012-08-29
3       2012-07-25

I need to write an SQL query in PostgreSQL to get record_id for MIN date in each month.

month    record_id
-----    ---------
8           2
7           3

as we see 2012-08-29 < 2012-08-30 and it is 8 month, so we should show record_id = 2

I tried something like this,

SELECT
   EXTRACT(MONTH FROM date) as month,
   record_id,
   MIN(date) 
FROM Records
GROUP BY 1,2

but it shows 3 records.

Can anybody help?


Solution

  • This will return multiples if you have duplicate minimum dates:

    Select
      minbymonth.Month,
      r.record_id
    From (
      Select
        Extract(Month From date) As Month, 
        Min(date) As Date
      From
        records
      Group By 
        Extract(Month From date)
      ) minbymonth
        Inner Join
      records r
        On minbymonth.date = r.date
    Order By
      1;
    

    Or if you have CTEs

    With MinByMonth As (
      Select
        Extract(Month From date) As Month, 
        Min(date) As Date
      From
        records
      Group By 
        Extract(Month From date)
      )
    Select
      m.Month,
      r.record_id
    From
      MinByMonth m
        Inner Join
      Records r
        On m.date = r.date
    Order By
      1;
    

    http://sqlfiddle.com/#!1/2a054/3