我在查询中遇到一个小问题,即根据同一个表中的记录更新表中的记录。以下是详细信息。
Cust_Master
Cust_ID - Reference_ID - Bal_Amount
----------
C100001 - R12345 - 30
C100002 - R12346 - 0
C100003 - R12345 - 0
C100004 - R12347 - 20
C100005 - R12345 - 0
我需要更新Bal_Amount where Reference_ID = Reference_ID of Cust_ID (C100001)
,但不应更新Cust_ID(C100001),这意味着源记录不应更新。
最后,值应为C100003,C100005应将Bal_Amount设为30。
我尝试使用以下查询,但该查询无法正常工作。
update Minbo_DB.dbo.Cust_Master
set Cust_Master.Bal_Amount = Cust_Master2.Bal_Amount
from Cust_Master
inner join Cust_Master Cust_Master2
ON Cust_Master2.Reference_ID = (select Reference_ID
from Cust_Master
where Cust_ID='C100001')
AND Cust_Master.Cust_ID <> 'C100001'
where
(Cust_Master.Cust_ID <> 'C100001')
答案 0 :(得分:0)
您的要求并不完全清楚,因此我们可以采用的方法可以改进......
CREATE TABLE #Example
(
Cust_ID VARCHAR(25),
Reference_ID VARCHAR(25),
Bal_Amount INT
)
INSERT INTO #Example
SELECT 'C100001', 'R12345', 30 UNION ALL
SELECT 'C100002', 'R12346', 0 UNION ALL
SELECT 'C100003', 'R12345', 0 UNION ALL
SELECT 'C100004', 'R12347', 20 UNION ALL
SELECT 'C100005', 'R12345', 0
;WITH Aggregation AS
(
SELECT Reference_ID, BalMax = MAX(Bal_Amount)
FROM #Example
GROUP BY Reference_ID
)
UPDATE E
SET Bal_Amount = BalMax
FROM Aggregation A
JOIN #Example E ON A.Reference_ID = E.Reference_ID
WHERE Bal_Amount != BalMax
SELECT *
FROM #Example
答案 1 :(得分:0)
大家好我有解决方案。以下是答案。
更新Cust_Master设置Cust_Jars_Bal = Cust_Master2.Cust_Jars_Bal 来自Cust_Master内部联接Cust_Master Cust_Master2 ON Cust_Master.Reference_ID = Cust_Master2.Reference_ID where(Cust_Master2.Cust_ID ='C100001')。
感谢您的贡献...