我有这些数据。
create table #temp_student_ticket
(
student_ticket_id int identity(1,1) primary key,
student_id int ,
ticket_amount numeric(9,2)
)
insert into #temp_student_ticket
(
student_id,
ticket_amount
)
values
(
1,30.00
),(2,180.00),(1,75.00),(2,66.00)
select * from #temp_student_ticket
我需要为同一个学生选择上一行。输出应如下所示。
student_id student_ticket_id amount prev_student_ticket_id prev_amount
1 1 20.00 NULL NULL
1 3 75.00 1 20.00
1 5 30.00 3 75.00
2 2 180.00 NULL NULL
2 4 66.00 2 180.00
在MYSQL中,在5000万行表中选择此格式的最佳方法是什么。
提前致谢。
答案 0 :(得分:0)
试试这个:
SELECT tst1.student_id, tst1.student_ticket_id, tst1.ticket_amount,
tst2.student_ticket_id prev_student_ticket_id, tst2.ticket_amount previous_amount
FROM temp_student_ticket tst1
LEFT JOIN temp_student_ticket tst2
ON (tst1.student_id = tst2.student_id
AND tst1.student_ticket_id > tst2.student_ticket_id
AND tst2.student_ticket_id = (SELECT MAX(tst3.student_ticket_id)
FROM temp_student_ticket tst3
WHERE tst3.student_id = tst1.student_id
AND tst3.student_ticket_id < tst1.student_ticket_id));