我有一个Visitdate列,其中包含一年中常去的患者。 我必须估算访问日期和后续日期,如下所示。
Table aaa
ID VDate Visit
10003 2003-09-26 00:00:00.000 1
10003 2004-05-15 00:00:00.000 2
10003 2007-01-09 00:00:00.000 3
10003 2007-07-05 00:00:00.000 4
我希望我的结果是
+-------+------------+------------+
| id | visit_date | follow_up |
+-------+------------+------------+
| 10003 | 2003-09-26 | 2004-05-15 |
| 10003 | 2004-05-15 | 2007-01-09 |
| 10003 | 2007-01-09 | 2007-07-05 |
| 10003 | 2007-07-05 | Null |
+-------+------------+------------+
答案 0 :(得分:0)
如果使用支持窗口功能的MySQL 8:
SELECT ID
, VDate AS visit_date
, lead(VDate, 1) OVER (PARTITION BY ID ORDER BY Visit) AS follow_up
FROM aaa
ORDER BY ID, Visit;
应该可以解决问题。
如果使用MySQL 5,也许类似
SELECT ID
, VDate AS visit_date
, (SELECT VDate FROM aaa AS a2 WHERE a.ID = a2.ID and a.Visit + 1 = a2.Visit) AS follow_up
FROM aaa AS a
ORDER BY ID, Visit;
格式化日期留给读者练习。
答案 1 :(得分:0)
如果您已经有了该值,并且知道要更新的行的id
,则应该为您设置该值:
UPDATE aaa SET follow_up = '2007-07-05' WHERE id = 10004;
请注意,在您的示例中,所有行都具有相同的ID。应该有一些唯一的ID或,并且可以在where子句中添加以检查您要查找的原始日期。
答案 2 :(得分:0)
DECLARE @Table TABLE (ID INT, VDate DATETIME, VISIT INT)
INSERT INTO @Table
VALUES (10003, '2003-09-26 00:00:00.000', 1), (10003, '2004-05-15 00:00:00.000', 2), (10003, '2007-01-09 00:00:00.000', 3), (10003, '2007-07-05 00:00:00.000', 4)
SELECT
T1.ID
,CAST(T1.VDate AS DATE) AS visit_date
,(SELECT TOP 1
CAST(T2.VDate AS DATE)
FROM @Table AS T2
WHERE T1.ID = T2.ID
AND T2.VDate > T1.VDate)
AS follow_up
FROM @Table AS T1
ORDER BY VISIT
如果您想更新列
DECLARE @Table TABLE (ID INT, VDate DATETIME, follow_up DATETIME, VISIT INT)
INSERT INTO @Table (ID, VDate, VISIT)
VALUES (10003, '2003-09-26 00:00:00.000', 1), (10003, '2004-05-15 00:00:00.000', 2), (10003, '2007-01-09 00:00:00.000', 3), (10003, '2007-07-05 00:00:00.000', 4)
UPDATE T1
SET T1.follow_up = (SELECT TOP 1
T2.VDate
FROM @Table T2
WHERE T1.ID = T2.ID
AND T2.VDate > T1.VDate)
FROM @TABLE T1
SELECT
ID
,CAST(VDate AS DATE) AS visit_date
,CAST(follow_up AS DATE) AS follow_up
FROM @Table