SQL:查找下一个最近的日期
我有这样的桌子SQL:查找下一个最近的日期,sql,Sql,我有这样的桌子 id | name | registration date ----------------------------- 1 | ABC | 2018-01-01 2 | DEF | 2018-01-02 3 | GHI | 2018-01-06 4 | JKL | 2018-01-07 5 | MNO | 2018-01-09 我想创建一个包含人名、注册日期和在他之后注册的人的姓名的表 所以我希望结果表如下所示: n
id | name | registration date
-----------------------------
1 | ABC | 2018-01-01
2 | DEF | 2018-01-02
3 | GHI | 2018-01-06
4 | JKL | 2018-01-07
5 | MNO | 2018-01-09
我想创建一个包含人名、注册日期和在他之后注册的人的姓名的表
所以我希望结果表如下所示:
name | registration date | next person
---------------------------------------
ABC | 2018-01-01 | DEF
DEF | 2018-01-02 | GHI
GHI | 2018-01-06 | JKL
JKL | 2018-01-07 | MNO
MNO | 2018-01-09 | -
在SQL中实现这一点最有效的方法是什么
提前谢谢您需要
子查询
:
select *, (select name
from table
where id > t.id
order by id
limit 1
) as next_person
from table t;
但是,您没有标记任何DBMS
,因此我选择了带有limit
子句的子查询
,但是一些DBMS
没有limit子句,例如SQL Server
,因此改用TOP
子句:
在SQL Server中,您可以使用以下函数:
select *, lead(name) over (order by id) as next_person
from table t;
您没有说明您的DBMS,但以下是ANSI标准SQL,它使用了所有数据库支持的窗口函数
尝试此查询,它正在工作
select
t1.name,
t1.registration_date as "registration date",
if(t2.name is null, '-', t2.name ) as "next person"
from test as t1
left join test as t2 on t2.registration_date > t1.registration_date
group by t1.id
标记您正在使用的DBMS(即MySQL
,SQL Server
等)。
select
t1.name,
t1.registration_date as "registration date",
if(t2.name is null, '-', t2.name ) as "next person"
from test as t1
left join test as t2 on t2.registration_date > t1.registration_date
group by t1.id