我有一张这样的表:
startyearmonthday| id
20130901 | 1
20131004 | 2
20130920 | 3
20131105 | 4
20131009 | 5
我想写一个查询,我可以返回一个这样的表:
startyearmonthday| id | endyearmonthday
20130901 | 1 | 20130920
20130920 | 3 | 20131004
20131004 | 2 | 20131009
20131009 | 5 | 20131105
20131105 | 4 | null
所以我希望结束日期基于当前开始日期之后的下一个最早的开始日期。我想有一些联系,但我无法弄清楚......
答案 0 :(得分:1)
试试这个(假设没有重复的行):
select a.*, b.startyearmonthday as endyearmonthday
from table_name a
left join table_name b
on b.startyearmonthday > a.startyearmonthday and not exists(select startyearmonthday from table_name c where a.startyearmonthday < c.startyearmonthday and c.startyearmonthday < b.startyearmonthday)
答案 1 :(得分:1)
我倾向于使用相关子查询来执行此操作:
select t.*,
(select startyearmonthday
from t t2
where t2.startyearmonthday > t.startyearmonthday
order by t2.startyearmonthday
limit 1
) as endyearmonthday
from t;
与之前的问题一样,t(startyearmonthday)
上的索引会很快运行。