简体   繁体   English

经过的月份数不断增加-MySQL

[英]Growing number of months passed - MySQL

I would like to create the MonthCount column described below. 我想创建下面描述的MonthCount列。 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. 我已经创建了ID和Date字段,但我很难想到一种巧妙的方法来计算已过的日期数。 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. 好像我记得在某处读过有关使用>或<运算符将表自身连接在一起的内容,但我无法完全回忆起该方法。

The best way to handle this in MySQL is to use variables: 在MySQL中处理此问题的最佳方法是使用变量:

  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;

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 现在为您准备的作业是弄清楚如何计算两个日期之间的差额

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM