2017-04-11 73 views
0
id month  status 
1 1997-11-01 A 
1 2015-08-01 B 
2 2010-01-01 A 
2 2010-02-01 B 
2 2012-10-01 C 

寻找下一行的值,我想格式化为:的MySQL通过ID

id month  lead_month status 
1 1997-11-01 2015-08-01  A 
1 2015-08-01  NOW()   B 
2 2010-01-01 2010-02-01  A 
2 2010-02-01 2012-10-01  B 
2 2012-10-01  NOW()   C 

MySQL是新的给我,和我有麻烦缠绕我的头周围的变量。我宁愿使用简单的LEAD()PARTITION,但不幸的是,我不能。

这里是我的尝试,不工作:

SET @lead = '1995-01-01'; --abitrary floor 

select id, month, status, @lead, @lead:=month from table 

输出看起来是这样的,这也不会,如果ID的自排检查排是相同的:

id month  lead_month status 
1 1997-11-01 1995-01-01 A 
1 2015-08-01 1997-11-01 B 
2 2010-01-01 2015-08-01 A 
2 2010-02-01 2010-01-01 B 
2 2012-10-01 2010-02-01 C 

回答

0

不要在MySQL中使用变量。这种逻辑将更好地驻留在您的应用程序使用的任何语言。但是,这可以在SQL中完成。

我的第一本能就是将这些数据保存在一个额外的列中。不要担心分贝的大小 - 宇宙中没有足够的月份成为问题。

你的ID也有问题:这些应该几乎总是主键,我。即独特。

如果你坚持你的计划,你可以使用加入。假设连续的唯一ID:

SELECT a.id, a.month, b.month AS lead_month, status FROM table AS a LEFT JOIN table AS b WHERE a.id - 1 = b.id;

0

您可以使用相关子查询:

select t.*, 
     (select t2.month 
     from t t2 
     where t.id = t2.id 
     order by t2.month desc 
     limit 1 
     ) as next_month 
from t; 

如果你想更换上个月每个ID值,那么你可以使用coalesce()

select t.*, 
     coalesce((select t2.month 
       from t t2 
       where t.id = t2.id 
       order by t2.month desc 
       limit 1 
       ), now()) as next_month 
from t;