>  기사  >  데이터 베이스  >  테이블에서 연속 행 간의 시간 차이를 계산하는 방법은 무엇입니까?

테이블에서 연속 행 간의 시간 차이를 계산하는 방법은 무엇입니까?

Barbara Streisand
Barbara Streisand원래의
2024-11-15 06:09:02421검색

How to Calculate Time Difference Between Consecutive Rows in a Table?

How to Calculate Time Difference in Two Consecutive Table Rows

In a table with a column called "StartDate," it's often necessary to determine the time difference between adjacent records. One user recently encountered this issue while working with a requestId and startdate table and sought assistance.

The table provided by the user contained data as follows:

requestId startdate
1 2011-10-16 13:15:56
2 2011-10-16 13:15:59
3 2011-10-16 13:15:59
4 2011-10-16 13:16:02
5 2011-10-16 13:18:07

The user's objective was to calculate the time difference between each adjacent pair of rows (e.g., requestId 1 and 2, 2 and 3, etc.). They recognized the need for a self-join but struggled to write the appropriate ON clause.

The provided solution leveraged an INNER JOIN between two instances of the same table (aliased as A and B). The ON clause specified that the requestId in row B should equal the requestId in row A plus one:

SELECT A.requestid, A.starttime, (B.starttime - A.starttime) AS timedifference
FROM MyTable A INNER JOIN MyTable B ON B.requestid = (A.requestid + 1)
ORDER BY A.requestid ASC

This query successfully calculated and returned the requested time difference between consecutive rows. However, if the requestId is not consecutive, an alternative approach is required:

SELECT A.requestid, A.starttime, (B.starttime - A.starttime) AS timedifference
FROM MyTable A CROSS JOIN MyTable B
WHERE B.requestid IN (SELECT MIN (C.requestid) FROM MyTable C WHERE C.requestid > A.requestid)
ORDER BY A.requestid ASC

In this modified query, a CROSS JOIN is used to match each row with every other row in the table. A subquery then selects the minimum requestId that is greater than the current selected requestId, ensuring that only consecutive rows are compared.

위 내용은 테이블에서 연속 행 간의 시간 차이를 계산하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.