SQL表更新除了每个Id的最新记录

时间:2014-04-26 11:25:11

标签: mysql sql

考虑下表,其中有4个差异客户,每个客户订单超过1个。 我需要根据创建的日期列将每个客户的XYZ列更新为1.

Update the table1 set xyz = 1

仅条件最新(创建日期)订单的XYZ值应为0

Customerid  Orderid     Date Created       XYZ 
12193438    13393354    09/08/2011 16:35    0
12193438    13384318    05/08/2011 14:08    0
12193438    13384458    08/08/2011 14:01    0
21801966    13379456    06/08/2011 12:59    0
21801966    13380639    06/08/2011 16:42    0
21971567    13385322    22/08/2011 18:00    0
21971567    13380200    09/08/2011 21:03    0
66697824    13389263    07/08/2011 13:44    0
66697824    13380162    08/08/2011 15:48    0

IT应如下所示

Customerid  Orderid       Date Created     XYZ
12193438    13393354    09/08/2011 16:35    0
12193438    13384318    05/08/2011 14:08    1
12193438    13384458    08/08/2011 14:01    1
21801966    13379456    06/08/2011 12:59    1
21801966    13380639    06/08/2011 16:42    0
21971567    13385322    22/08/2011 18:00    0
21971567    13380200    09/08/2011 21:03    1
66697824    13389263    07/08/2011 13:44    1
66697824    13380162    08/08/2011 15:48    0

6 个答案:

答案 0 :(得分:1)

UPDATE thetable tt
SET xyz = 1
WHERE EXISTS (
  SELECT * FROM thetable ex
  WHERE ex.customerId = tt.customerId
  AND ex.dateCreated > tt.dateCreated
  );

答案 1 :(得分:0)

您可以使用updatejoin来完成此操作。此版本使用聚合来查找要更新的正确行:

update xyz join
       (select customerid, max(datecreated) as maxdc
        from xyz
        group by customerid
       ) cd
       on xyz.customerid = cd.customerid and xyz.datecreated < cd.maxdc
    set xyz.XYZ = 1;

要随时间维护数据,您可以考虑考虑使用触发器。

如果你想同时设置01(所以不要假设一切都从0开始,你可以这样做:

update xyz join
       (select customerid, max(datecreated) as maxdc
        from xyz
        group by customerid
       ) cd
       on xyz.customerid = cd.customerid 
    set xyz.XYZ = xyz.datecreated < cd.maxdc;

答案 2 :(得分:0)

因此,对于每个客户,最新(创建日期)订单的XYZ值应为0,其他订单应为1

Update the table1 
set xyz = 1 where OrderID not in (select OrderID from (select * from table1 order by DateCreated desc)a group by CustomerID,OrderID)b

假设 - XYZ默认值为0

答案 3 :(得分:0)

Update the table1 set xyz = 1 where datecreated < '<your date you want>'

这将为所有xyz设置1,datecreated小于您指定的值。 PS:datecreated应该是它快速工作的索引。

答案 4 :(得分:0)

这涉及将数据转换为table2,然后更新table2以填充XYZ列。

select *,RANK()over(partition by customerid order by date_created desc) as dateorder into table2
from table1 
update table2 set XYZ = 1 where dateorder not like 1

表1本身没有更新可能看起来很奇怪...... RANK函数是一个分析处理工具,如果不创建分析表,它就无需工作。这主要是因为table1忙于接收订单数据!在这里,table1(事务表)可以继续接收数据(交易),并且在不太繁忙的时候,自上次分析以来添加的数据可以移出它并进入table2(分析表):

答案 5 :(得分:0)

DECLARE @customerid INT - 用于文件名

DECLARE db_cursor CURSOR for 选择不同的customerid 来自订单

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @customerid

WHILE @@ FETCH_STATUS = 0
BEGIN
        更新订单         设置XYZ = 1         其中Orderid&lt;&gt; (从Customerid = @customerid order by DateCreated desc的订单中选择前1名Orderid)         和Customerid = @customerid

   FETCH NEXT FROM db_cursor INTO @customerid   

结束

关闭db_cursor
DEALLOCATE db_cursor