更新另一个表中日期时间在另一列中具有多个值的列



我有两个表,必须用table2中代码的值填充table1中的Code列。Date列的类型为datetime,来自table1的日期列没有时间值,而来自table2的日期有时间。

表1:

Code  Date 
NULL  2018-5-6 00:00:00
NULL  2018-5-6 00:00:00
NULL  2018-5-6 00:00:00
NULL  2018-5-6 00:00:00
NULL  2017-7-4 00:00:00
NULL  2016-1-3 00:00:00

表2:

Code  Date 
F444  2018-5-6 01:30:00
T777  2018-5-6 07:00:00
R545  2017-7-4 00:00:00
D432  2016-1-3 00:00:00

当我尝试加入表并更新表1中的代码时,我只能从表2中获得一个日期来填写代码。

结果:

Code  Date 
F444  2018-5-6 00:00:00
F444  2018-5-6 00:00:00
F444  2018-5-6 00:00:00
F444  2018-5-6 00:00:00
R545  2017-7-4 00:00:00
D432  2016-1-3 00:00:00

如果一个日期在另一个表中有多次,我如何更新代码列以显示所有代码?

预期结果:

Code  Date 
F444  2018-5-6 00:00:00
F444  2018-5-6 00:00:00
T777  2018-5-6 00:00:00
T777  2018-5-6 00:00:00
R545  2017-7-4 00:00:00
D432  2016-1-3 00:00:00

谢谢你的帮助!

这相当棘手。您需要枚举两个表中的匹配值,然后将这些信息用于更新。

with toupdate as (
select t1.*,
row_number() over (partition by date order by date) as seqnum
from table1 t1
)
update t
set code = t2.code
from toupdate t join
(select t2.*,
row_number() over (partition by date order by date) as seqnum,
count(*) over (partition by date) as cnt
from table2 t2
) t2
on t.date = t2.date and
t1.seqnum % t2.cnt = t2.seqnum;

用于更新-相同的ntile概念,但将记录放入#temp以避免更新时出现性能问题。

逻辑遵循

下拉表#temp选择b.code,a.date,ntile(2(over(按a.date分区,按a.date排序(作为t1到#temp from(选择*,ntile

更新set code=b.codefrom(select*,ntile(2(over(partition by date order by date(as t1 from t1(a内部连接#温度b在(a.date=b.date和a.t1=b.t1(

这是代码。

我们可以在sql中使用ntile函数来平均分配值。

选择b.code,a.date from(选择*,ntile(2(over(partition by date order by date(as tt from t1(a左联接(select*,rank((over(partition by convert(date,date(order by date(作为从t2开始的ttr)转换时的b(日期,a.[date](=转换(日期,b.[date]

最新更新