sql上一行

时间:2017-04-26 03:03:31

标签: sql

我有一个SQL问题,典型的:前一行,下一行问题但是: 不使用rownum,领导或排名这些功能,只选择并加入

表:Student

字段:Student_ID, Department, Start_Date

前:

1,C, 2017-01-1 
1,B, 2017-07-1 
1,A, 2017-12-1 

预期产出:

Student_ID, Department, Start_Date, End_Date 

前:

1,C, 2017-01-1, 2017-07-01 
1,B, 2017-07-1,2017-12-01 
1,A, 2017-12-1, ... 

End_Date是学生ID的下一条记录的开始日期

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

数据

create table student (
    Student_ID int,
    Department char(1),
    Start_Date date
);
insert into student values (1, 'A', '2017-01-01');
insert into student values (1, 'B', '2017-01-01');
insert into student values (1, 'C', '2017-12-31');

SQL Server

select 
    student_id,
    department,
    start_date,
    (select top 1 start_date 
     from student
     where student_id = s.student_id
     ) as end_date
from student s
order by student_id, department;

示例:http://rextester.com/HLL58959

PostgreSQL和MySQL以及SQLite

select 
    student_id,
    department,
    start_date,
    (select start_date
     from student
     where student_id = s.student_id
     limit 1) as end_date
from student s
order by student_id, department;

示例:http://rextester.com/XWUAZ90711