0

I would like to create the MonthCount column described below. I have the ID and Date fields already created I am just having trouble thinking of a clever way to count the number of dates that have passed. The dates are always the first of the month, but the first month could be any month between Jan and Dec.

ID    Date    MonthCount
1     1/2016  1 
1     2/2016  2
1     3/2016  3
2     5/2015  1
2     6/2015  2
2     7/2015  3

It seems like I remember reading somewhere about joining the table to itself using a > or < operator but I can't completely recall the method.

Matthew Snell
  • 917
  • 3
  • 12
  • 26

2 Answers2

0

The best way to handle this in MySQL is to use variables:

  select t.*,
         (@rn := if(@id = id, @rn + 1,
                    if(@id := id, 1, 1)
                   )
         ) as rn
  from t cross join
       (select @rn := 0, @id := -1) params
  order by id, date;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

It looks like you're looking for:

select a.id, a.date, b.mindate
from table as a
inner join (
    select id, min(date) as mindate
    from table
    group by id
) as b on (a.id=b.id)

this will give you

ID    Date    mindate
1     1/1/2016  1/1/2016
1     1/2/2016  1/1/2016
1     1/3/2016  1/1/2016
2     1/5/2015  1/5/2015
2     1/6/2015  1/5/2015
2     1/7/2015  1/5/2015

now homework for you is to figure out how to calculate difference between two dates

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57