简体   繁体   English

如何从同一表中的另一列向后更新表中的列

[英]How to update a column in a table from another column in the same table one step back

Hi I have a table that has a structure like below嗨,我有一张表,其结构如下

Id ID oldid老字号 newid新ID dateon达顿 currentdate当前的日期 code代码
1 1个 NULL NULL 636 636 2022-03-07 16:02:48.960 2022-03-07 16:02:48.960 2022-03-25 10:27:56.393 2022-03-25 10:27:56.393 777 777
2 2个 636 636 202 202 2022-03-25 10:27:56.393 2022-03-25 10:27:56.393 2022-05-11 14:34:48.153 2022-05-11 14:34:48.153 777 777
3 3个 202 202 203 203 2022-05-11 14:34:48.153 2022-05-11 14:34:48.153 2022-05-12 14:35:42.957 2022-05-12 14:35:42.957 777 777
4 4个 203 203 273 273 2022-05-12 14:35:42.957 2022-05-12 14:35:42.957 2022-05-14 14:35:42.957 2022-05-14 14:35:42.957 777 777
5 5个 273 273 189 189 2022-05-14 14:35:42.957 2022-05-14 14:35:42.957 NULL NULL 777 777

Currently the column in currentdate is empty.当前 currentdate 中的列为空。 I want to update the column of current date like mentioned above ie update column currentdate one step back from dateon column.我想像上面提到的那样更新当前日期的列,即更新列 currentdate 从 dateon 列后退一步。

I tried this query, But it is updating random data我试过这个查询,但它正在更新随机数据

UPDATE a 
SET a.currentdate = b.dateon
FROM Table a
LEFT JOIN Table b ON b.code = a.c aodend b.oldid = a.newid

You could use the lead function within CTE as the following:您可以在 CTE 中使用潜在客户 function,如下所示:

with cte as
(
  select *,
    lead(dateon) over (partition by code order by dateon) ld
  from table_name
)
update cte set currentdate = ld;

See demo看演示

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

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