简体   繁体   English

如何更新值取决于 postgres 中的最新日期

[英]How to update value depends on latest date in postgres

I have table like follows我有如下表格

col date
a   2022-07-26
a   2022-07-27
c   2022-08-02
d   2022-07-28

and I would like to update value at latest date column我想更新最新日期列的值

update table
set date = '2022-09-30'
where col='a'
and // some logic

my desired result is as follows我想要的结果如下

col date        
a   2022-07-26   
a   2022-09-30
c   2022-08-02
d   2022-07-28

how to select latest days and update? select怎么最新天和更新?

Thanks谢谢

We can use an update join approach here:我们可以在这里使用更新连接方法:

UPDATE yourTable t1
SET date = '2022-09-30'::date
FROM (
    SELECT col, MAX(date) AS max_date
    FROM yourTable
    GROUP BY col
) t2
WHERE t2.col = t1.col AND
      t2.max_date = t1.date AND
      t1.col = 'a';

The subquery above aliased as t2 will target only the latest date record for each col group.上面别名为t2的子查询将只针对每个col组的最新日期记录。 We then set the date for that record, for col = a .然后我们为该记录设置日期,对于col = a

An easy and readable approach would be to simply update the record for the MAX(date).一种简单易读的方法是简单地更新 MAX(date) 的记录。

UPDATE table 
   SET date = '2022-09-30' 
 WHERE col = 'a' 
   AND date = (SELECT MAX(date) FROM table WHERE col = '0');

This is assuming you only want to update for a, and for this 1 record.这是假设您只想更新 a 和这 1 条记录。 If you want to update for each 'col' on the highest date, you for example use a CTE;如果您想在最高日期更新每个“col”,例如使用 CTE;

WITH CTE_max_dates AS (SELECT col, max(date) FROM table)
UPDATE t
   SET date = '2022-09-30'
  FROM table t
  JOIN CTE_max_dates cte
    ON t.col = cte.col
   AND t.date = cte.date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM