Get the following record in query

江枫思渺然 提交于 2020-07-22 06:02:30

问题


If we have a table called Activity and has rows[ActivityCode and StartTime] for example

ActivityCode-----StartTime<BR>
Lunch------------1200<BR>
MathClass--------1300<BR>
EnglishClass-----1500<BR>
EndOfSchool------1700<BR>

And now I want to make one SQL Query to display as follow:

ActivityCode-----StartTime-----EndTime<BR>
Lunch------------1200----------1300<BR>
MathClass--------1300----------1500<BR>
EnglishClass-----1500----------1700<BR>
EndOfSchool------1700----------1700<BR>

I am not sure how to do it. I tried to follow How to get a value from previous result row of a SELECT statement?. But it didn't work as I expected. Any help is appreciated.


回答1:


You can use this query:

SELECT 
    Activity.ActivityCode, 
    Activity.StartTime, 
    Nz((Select Top 1 StartTime 
        From Activity As T 
        Where T.StartTime > Activity.StartTime 
        Order By StartTime Asc),
        [StartTime]) AS EndTime, 
    CDate(TimeSerial(Val([EndTime])\100,Val([EndTime]) Mod 100,0)-
        TimeSerial(Val([StartTime])\100,Val([StartTime]) Mod 100,0)) AS Duration
FROM 
    Activity;

Output:




回答2:


I would use a subquery with aggregation:

select a.*,
       (select nz(min(a2.starttime), a.endtime)
        from activity as a2
        where a2.starttime > a.starttime
       ) as endtime
from activity as a;

Normally in such an example, there would be an additional column identifying a "grouping" of some sort -- such as a person. If you have such a column, you would have an equality condition in the subquery as well as the inequality on time.

Also, there are much better ways to do this in almost any other database -- notably, the lead() function.



来源:https://stackoverflow.com/questions/62808883/get-the-following-record-in-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!