PostgreSQL多重更新

时间:2016-12-14 14:11:52

标签: postgresql

我有情况...... 我有这些列 - 表X

 Product   Number  LastEditDate    GUID
 A         0       14.12.16        A1
 A         0       10.12.16        A2
 B         0       10.12.16        A3
 B         0       13.12.16        A4
 C         0       13.12.16        A5
 C         0       14.12.16        A6

现在,我需要将数字1添加到Date为Max的所有产品中。 我正在使用此查询:

update X set Number=0;
update X set Number=1 where LastEditDate in (select Max(LastEditDate) from X Group by Product);

所以这会给我这样的东西:

Product    Number    LastEditDate
A          1         14.12.16
A          0         10.12.16
B          0         10.12.16
B          1         13.12.16
C          0         13.12.16
C          1         14.12.16

但是,根据我的查询,我有: 1; 0; 0; 1; 1; 1;因为13.12.16将在那个"从X中选择Max(LastEditDate)。 如何做到这一点,得到结果:1; 0; 0; 1; 0; 1; ???

请帮忙!

2 个答案:

答案 0 :(得分:1)

你应该寻找对(product, lasteditdate)

update x 
set number = 1 
where (product, lasteditdate) in (
    select product, max(lasteditdate) 
    from x 
    group by product);

答案 1 :(得分:0)

您可以在此处查看:http://rextester.com/YVLK16496

with t1 as (
    select Product, Max(LastEditDate) as MaxDate from t group by Product
)
update t
set Number=1
from t1
where t.Product = t1.Product and t.LastEditDate = t1.MaxDate;