[英]SQL table update all but the most recent record for every Id
考虑下表,其中有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
UPDATE thetable tt
SET xyz = 1
WHERE EXISTS (
SELECT * FROM thetable ex
WHERE ex.customerId = tt.customerId
AND ex.dateCreated > tt.dateCreated
);
您可以使用update
和join
来做到这一点。 此版本使用聚合来查找要更新的正确行:
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;
为了长时间保持数据,您可以考虑使用触发器。
如果要同时设置0
和1
(以免假设所有内容都从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;
因此,对于每个客户,最新(创建日期)的订单的XYZ值应为0,其他订单的XYZ值应为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
Update the table1 set xyz = 1 where datecreated < '<your date you want>'
这会将所有datecreated
小于您指定的日期的xyz设置为1。 PS: datecreated
应该是使其快速工作的索引。
这涉及将数据填充到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
table1本身未更新似乎很奇怪... RANK函数是一种分析处理工具,在没有创建分析表的情况下它不一定起作用。 这主要是因为table1正在忙于接收订单数据! 在这里,表1(事务表)可以进行接收数据(事务),并且在不那么忙碌的时候,可以将自上次分析以来移出的数据移到表2(分析表)中:
DECLARE @customerid INT-用于文件名
声明db_cursor CURSOR FOR
从订单中选择不同的客户ID
打开db_cursor
从db_cursor INTO @customerid获取下一个
@@ FETCH_STATUS = 0时
开始
UPDATE订单集XYZ = 1,其中,Orderid <>(从DateCreated desc中选择Customerid = @customerid订单的订单中选择前1个Orderid)和Customerid = @customerid
FETCH NEXT FROM db_cursor INTO @customerid
结束
关闭db_cursor
取消分配db_cursor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.