当 JOIN 是多列时处理来自另一个表的更新



当 JOIN 是多列时,我正在处理来自另一个表的更新

我已经尝试了多个版本的 SQL 语句,但没有一个正常工作。

我需要用另一个表中的数据更新一个表中的单个字段,但 JOIN 位于三个字段上。 有时我需要从其他字段使用 SUM(( 进行更新。

所以问题来了: 我正在处理这个没有身份字段的令人抓狂的物业管理软件!! (为什么? 为什么不使用标识字段?!?!?!(

因此,我的链接总是涉及:dept_no(每个物业唯一(、单元(每个单元(、租赁开始日期(因为每个属性/单元组合可以有多个租约(。

我已经有一个我生成的"Lease_unit"表,它给了我每个属性/单元组合的 MAX(lease_start_date(。 但是,我经常需要使用来自其他来源的数据更新该表中的字段,其中链接是dept_no、单位lease_start_date组合(不需要 MAX((,因为我已经处理好了(。

所以,有两种问题/例子我无法弄清楚,你们中的一些人可以在一秒钟内回答(我已经用头撞墙了一段时间(。 有人可以帮助我吗?

问题/示例 #1:

Update lease_unit.field with other_table.other_field
where lease_unit.dept_no = other_table.dept_no AND lease_unit.unit = other_table.unit AND lease_unit.lease_start_date = other_table.lease_start_date.

问题/示例 #2:

Update lease_unit.field with SUM(other_table.numeric_field)
where lease_unit.dept_no = other_table.dept_no AND lease_unit.unit = other_table.unit AND lease_unit.lease_start_date = other_table.lease_start_date.

我真的可以在这里使用一些指导。 我非常感谢任何能给我几分钟时间的人。 希望有一天我能把它传给别人。 - 约翰·基尔南

示例 1
您可以将更新与联接一起使用

Update lease_unit 
SET  lease_unit.field= other_table.other_field
FROM lease_unit 
INNER JOIN other_table ON lease_unit.dept_no = other_table.dept_no 
AND lease_unit.unit = other_table.unit 
AND lease_unit.lease_start_date = other_table.lease_start_date

示例 2 使用基于总和子查询的连接更新

Update lease_unit 
SET  lease_unit.field= t.my_sum
FROM lease_unit 
INNER JOIN (
select  dept_no, unit, lease_start_date, sum(numeric_field) my_sum
from  other_table
GROUP BY dept_no, unit, lease_start_date
) t ON lease_unit.dept_no = t.dept_no 
AND lease_unit.unit = t.unit 
AND lease_unit.lease_start_date = t.lease_start_date

(无论如何,使用indentity列或3列主键不是问题(

最新更新