[英]Time between two non consecutive rows? (MySQL)
I've looked here Calculate the time difference between of two rows . 我看过这里计算两行之间的时间差 。
I modified the code here: 我在这里修改了代码:
SELECT A.Test_ID, B.TestDate - A.TestDate AS DaysBetweenTests FROM Exams A JOIN Exams B ON B.Test_ID = A.Test_ID WHERE (SELECT B.Test_ID FROM B.Exams ORDER BY Animal_ID, B.TestDate LIMIT 1 OFFSET 1)
This query isn't complete. 该查询不完整。 I'm trying to calculate the days between TestDate with the next TestDate for the same
Animal_ID
. 我正在尝试计算相同的
Animal_ID
TestDate与下一个TestDate之间的天Animal_ID
。 The problem here is that an Animal_ID
TestDate is not directly consecutive with Test_ID
. 这里的问题是
Animal_ID
TestDate与Test_ID
不直接连续。 I can't use Test_ID +1
. 我不能使用
Test_ID +1
。
Sample Exams table: 考试表样本:
Test_ID | TestDate | Animal_ID
1 2013-01-01 100
2 2007-06-18 162
3 2013-02-01 100
4 2013-04-16 100
The TestDate for a single Animal_ID
is always increasing in order, thus a higher Test_ID number
. 对于单个的TestDate
Animal_ID
总是为了增加,因而较高的Test_ID number
。
I'm having trouble with the subquery. 我在使用子查询时遇到了麻烦。
This query repeats the subquery that determines the next test date. 此查询重复确定下一个测试日期的子查询。 You don't necessarily need to do that in production;
您不一定需要在生产中执行此操作。 it just helps to see the data when you're figuring things out.
解决问题时,它仅有助于查看数据。
SELECT T1.Animal_ID,
T1.TestDate,
(SELECT min(TestDate)
FROM Exams
WHERE Animal_ID = T1.Animal_ID
AND TestDate > T1.TestDate
GROUP BY Animal_ID
) AS Next_TestDate,
datediff((SELECT min(TestDate)
FROM Exams
WHERE Animal_ID = T1.Animal_ID
AND TestDate > T1.TestDate
GROUP BY Animal_ID
), T1.TestDate) AS Elapsed_Days
FROM Exams T1
ORDER BY Animal_ID, TestDate;
select
t.*,
coalesce(timestampdiff(day, @prevDate, if(@prevAnimal = Animal_ID, TestDate, @prevDate)), 0) as timedifference_in_days,
@prevAnimal := Animal_ID,
@prevDate := TestDate
from
t
, (select @prevDate := null, @prevAnimal := null) as var_init
order by Animal_ID, TestDate
CREATE TABLE t
(`Test_ID` int, `TestDate` date, `Animal_ID` int)
;
INSERT INTO t
(`Test_ID`, `TestDate`, `Animal_ID`)
VALUES
(1, '2013-01-01', 100),
(2, '2007-06-18', 162),
(3, '2013-02-01', 100),
(4, '2013-04-16', 100)
;
Output: 输出:
| TEST_ID | TESTDATE | ANIMAL_ID | TIMEDIFFERENCE_IN_DAYS | @PREVANIMAL := ANIMAL_ID | @PREVDATE := TESTDATE |
|---------|---------------------------------|-----------|------------------------|--------------------------|-----------------------|
| 1 | January, 01 2013 00:00:00+0000 | 100 | 0 | 100 | 2013-01-01 |
| 3 | February, 01 2013 00:00:00+0000 | 100 | 31 | 100 | 2013-02-01 |
| 4 | April, 16 2013 00:00:00+0000 | 100 | 74 | 100 | 2013-04-16 |
| 2 | June, 18 2007 00:00:00+0000 | 162 | 0 | 162 | 2007-06-18 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.