我看过这里Calculate the time difference between of two rows。
我在这里修改了代码:
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)
此查询未完成。我正在尝试计算 TestDate 与下一个 TestDate 之间相同Animal_ID
的天数。这里的问题是Animal_ID
TestDate 与Test_ID
没有直接连续。我无法使用Test_ID +1
。
示例考试表:
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
单个Animal_ID
的 TestDate 始终按顺序增加,因此Test_ID number
更高。
我遇到了子查询的问题。
答案 0 :(得分:1)
此查询重复确定下一个测试日期的子查询。你不一定需要在生产中这样做;当你想出事情时,它只是有助于查看数据。
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;
答案 1 :(得分:0)
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)
;
输出:
| 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 |