MYSQL更新行具有重复值但最早的日期

时间:2018-05-22 16:11:17

标签: mysql max

尝试了许多建议让它工作,很难解释,所以下面是我拥有的数据和我想要实现的结果。

如果不是MAX Ldate,我想将'Active'列更新为0。

ID  | SNumber | Ldate      | Active
4804  188       2015-11-17   1
4806  189       2015-11-25   1
4807  190       2015-11-25   1
4808  191       2015-11-19   1
4809  192       2015-11-19   1
4820  193       2015-11-17   1
4821  193       2016-06-08   1
4830  194       2015-11-17   1
4831  194       2016-06-08   1
4828  195       2015-11-17   1
4829  195       2016-06-08   1


ID   SNumber  Ldate       Active    
4804 188      2015-11-17  1
4806 189      2015-11-25  1
4807 190      2015-11-25  1
4808 191      2015-11-19  1
4809 192      2015-11-19  1
4820 193      2015-11-17  0
4821 193      2016-06-08  1
4830 194      2015-11-17  0
4831 194      2016-06-08  1
4828 195      2015-11-17  0
4829 195      2016-06-08  1

我可以通过“选择ID,SNumber,Ldate从(选择*来自SNB,Ldate desc的tbl顺序)x group by SNumber”得到所有行的MAX Ldate“

感谢您花时间看看!

1 个答案:

答案 0 :(得分:2)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,SNumber INT NOT NULL
,Ldate DATE NOT NULL
);

INSERT INTO my_table VALUES
(4804,188,'2015-11-17'),
(4806,189,'2015-11-25'),
(4807,190,'2015-11-25'),
(4808,191,'2015-11-19'),
(4809,192,'2015-11-19'),
(4820,193,'2015-11-17'),
(4821,193,'2016-06-08'),
(4830,194,'2015-11-17'),
(4831,194,'2016-06-08'),
(4828,195,'2015-11-17'),
(4829,195,'2016-06-08');

SELECT x.*
     , COALESCE(x.ldate = y.ldate,0) active 
  FROM my_table x 
  LEFT 
  JOIN 
     ( SELECT snumber
            , MAX(ldate) ldate 
         FROM my_table 
        GROUP 
           BY snumber
     ) y 
    ON y.snumber = x.snumber 
   AND y.ldate = x.ldate;

+------+---------+------------+--------+
| id   | SNumber | Ldate      | active |
+------+---------+------------+--------+
| 4804 |     188 | 2015-11-17 |      1 |
| 4806 |     189 | 2015-11-25 |      1 |
| 4807 |     190 | 2015-11-25 |      1 |
| 4808 |     191 | 2015-11-19 |      1 |
| 4809 |     192 | 2015-11-19 |      1 |
| 4820 |     193 | 2015-11-17 |      0 |
| 4821 |     193 | 2016-06-08 |      1 |
| 4830 |     194 | 2015-11-17 |      0 |
| 4831 |     194 | 2016-06-08 |      1 |
| 4828 |     195 | 2015-11-17 |      0 |
| 4829 |     195 | 2016-06-08 |      1 |
+------+---------+------------+--------+

我无法想到你为什么存储这个内容,但将上述更改为更新很容易。它可能看起来像这样(显然,你需要先改变上面的表格设计)......

UPDATE my_table x 
  LEFT
  JOIN 
     ( SELECT snumber
            , MAX(ldate) ldate 
         FROM my_table 
        GROUP 
           BY snumber
     ) y 
    ON y.snumber = x.snumber 
   AND y.ldate = x.ldate
   SET x.active = 0
 WHERE y.snumber IS NULL;

但我认为我通常会使用INNER JOIN进行更新,在这种情况下它可能看起来像这样(可能绑定在事务中)...

 UPDATE my_table SET active = 0;
 UPDATE my_table x 
   JOIN 
      ( SELECT snumber
             , MAX(ldate) ldate 
          FROM my_table 
         GROUP 
            BY snumber
      ) y 
     ON y.snumber = x.snumber 
    AND y.ldate = x.ldate
    SET x.active = 1;