更新备用记录日期的值

时间:2019-05-30 06:03:33

标签: mysql sql

我需要更新与日期匹配的值,因此请仔细查看清晰图片的示例数据。

我需要在匹配的日期之前更新BP值。

我更新了下面给出的步骤,其中VisitDate和RecordDate相同。

    update ccc
    set RDate = b.Record_date,
    BP = b.BloodPressure
    FROM ccc a JOIN bbb b
    ON a.ID = b.ID and 
    b.Record_date = a.Vdate

但是我无法匹配RecordDate是> VisitDate并且<而不是下一个Vdate的情况。

在这种情况下,我需要在Vdate之间更新Rdate的值。

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
Table bbb
    ID    Rdate                   BP
    10003 2003-09-26 00:00:00.000 89
    10003 2004-05-17 00:00:00.000 70
    10003 2007-01-12 00:00:00.000 95

I would want 

    ID    VDate                 Visit   RDate               BP
    10003 2003-09-26 00:00:00.000 1 2003-09-26 00:00:00.000 89
    10003 2004-05-15 00:00:00.000 2 2004-05-17 00:00:00.000 70
    10003 2007-01-09 00:00:00.000 3 2007-01-12 00:00:00.000 95
    10003 2007-07-05 00:00:00.000 4 Null                    Null

1 个答案:

答案 0 :(得分:0)

这是一个查询,返回显示的结果。我不明白什么需要“更新” ...

DROP TABLE IF EXISTS aaa;

CREATE TABLE aaa 
(id INT NOT NULL
,visit_date DATE NOT NULL
);

INSERT INTO aaa VALUES
(10003,'2003-09-26'),
(10003,'2004-05-15'),
(10003,'2007-01-09'),
(10003,'2007-07-05');

DROP TABLE IF EXISTS bbb;

CREATE TABLE bbb 
(id INT NOT NULL
,visit_date DATE NOT NULL
,BP INT NOT NULL
);

INSERT INTO bbb VALUES
(10003,'2003-09-26',89),
(10003,'2004-05-17',70),
(10003,'2007-01-12',95);

SELECT x.*
     , y.visit_date bp_date
     , y.bp
  FROM
     ( SELECT a1.*
            , COALESCE(MIN(a2.visit_date),CURDATE()) follow_up 
         FROM aaa a1 
         LEFT 
         JOIN aaa a2 
           ON a2.id = a1.id 
          AND a2.visit_date > a1.visit_date 
        GROUP 
           BY id
            , visit_date
     ) x
  LEFT
  JOIN bbb y
    ON y.id = x.id
   AND y.visit_date BETWEEN x.visit_date AND x.follow_up;
+-------+------------+------------+------------+------+
| id    | visit_date | follow_up  | bp_date    | bp   |
+-------+------------+------------+------------+------+
| 10003 | 2003-09-26 | 2004-05-15 | 2003-09-26 |   89 |
| 10003 | 2004-05-15 | 2007-01-09 | 2004-05-17 |   70 |
| 10003 | 2007-01-09 | 2007-07-05 | 2007-01-12 |   95 |
| 10003 | 2007-07-05 | 2019-05-30 | NULL       | NULL |
+-------+------------+------------+------------+------+