我有一个看起来像这样的表:
updated_on | start_date
2017-09-28 21:09:05 | 2017-08-06 06:59:04
2017-10-02 15:19:05 | 2017-09-28 21:11:21
2017-10-05 12:00:00 | 2017-10-02 15:21:05
我想做的是用start_date的第二个实例减去第一个更新的实例,意思是
TIMESTAMPDIFF(SECOND, 2017-09-28 21:09:05, 2017-09-28 21:11:21)
TIMESTAMPDIFF(SECOND, 2017-10-02 15:19:05, 2017-10-02 15:21:05)
如果存在多行,并继续这样做。
我如何实现这一目标?
答案 0 :(得分:2)
您可以使用共同相关的子查询来获取下一条记录。
<强>查询强>
SELECT
*
, (SELECT
start_date
FROM
Table1 table12
WHERE
Table1.updated_on < table12.updated_on
ORDER BY
updated_on ASC
LIMIT 1
)
as next_start_date
FROM
Table1
ORDER BY
updated_on ASC
结果(SQL小提琴)
| updated_on | start_date | next_start_date |
|----------------------|----------------------|----------------------|
| 2017-09-28T21:09:05Z | 2017-08-06T06:59:04Z | 2017-09-28T21:11:21Z |
| 2017-10-02T15:19:05Z | 2017-09-28T21:11:21Z | 2017-10-02T15:21:05Z |
| 2017-10-05T12:00:00Z | 2017-10-02T15:21:05Z | (null) |
demo http://www.sqlfiddle.com/#!9/94af3d/8
现在我们可以使用TIMESTAMPDIFF函数了。
<强>查询强>
SELECT
*
, TIMESTAMPDIFF(
SECOND
, updated_on
, (SELECT
start_date
FROM
Table1 table12
WHERE
Table1.updated_on < table12.updated_on
ORDER BY
updated_on ASC
LIMIT 1
)
) as diff
FROM
Table1
ORDER BY
updated_on ASC
<强>结果强>
| updated_on | start_date | diff |
|----------------------|----------------------|--------|
| 2017-09-28T21:09:05Z | 2017-08-06T06:59:04Z | 136 |
| 2017-10-02T15:19:05Z | 2017-09-28T21:11:21Z | 120 |
| 2017-10-05T12:00:00Z | 2017-10-02T15:21:05Z | (null) |
答案 1 :(得分:0)
SELECT x.*
, TIMEDIFF(MIN(y.start_date),x.updated_on) n
FROM my_table x
JOIN my_table y
ON y.updated_on > x.updated_on
GROUP
BY x.updated_on;
......或类似的东西