0

我有一张这样的桌子:

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

所以我希望结束日期基于当前开始日期之后的下一个最早开始日期。我想涉及某种加入,但我无法弄清楚......

4

2 回答 2

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)
于 2013-09-01T20:46:28.213 回答
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)

于 2013-09-01T20:53:57.590 回答