所以我有一个名为dummy的表,看起来像
A | B | C | D | E
------------------
1 | 2 | 3 | 4 | u1
1 | 2 | 4 | 3 | u2
1 | 2 | 4 | 3 | u3
我已经确定每一行都需要具有相同的C
列WHERE E = u1
。所以我最终得到:
A | B | C | D | E
------------------
1 | 2 | 3 | 4 | u1
1 | 2 | 3 | 3 | u2
1 | 2 | 3 | 3 | u3
为此,我运行了以下查询:
update tb1
set tb1.C = tb2.C
from dummy as tb1, dummy as tb2
where tb2.E = 'u1'
我很好奇这是否是在SQL Server中执行此类操作的最佳方式。
答案 0 :(得分:0)
试试这个
update dummy set C = (SELECT TOP 1 C FROM dummy WHERE E = 'u1')
答案 1 :(得分:0)
测试数据
DECLARE @TABLE TABLE (A INT,B INT,C INT,D INT,E VARCHAR(2))
INSERT INTO @TABLE VALUES
(1,2,3,4,'u1'),(1,2,4,3,'u2'),(1,2,4,3,'u3')
更新查询
UPDATE @TABLE
SET C = (SELECT TOP 1 C
FROM @TABLE
WHERE E = 'u1')
结果集
SELECT * FROM @TABLE
╔═══╦═══╦═══╦═══╦════╗
║ A ║ B ║ C ║ D ║ E ║
╠═══╬═══╬═══╬═══╬════╣
║ 1 ║ 2 ║ 3 ║ 4 ║ u1 ║
║ 1 ║ 2 ║ 3 ║ 3 ║ u2 ║
║ 1 ║ 2 ║ 3 ║ 3 ║ u3 ║
╚═══╩═══╩═══╩═══╩════╝
答案 2 :(得分:0)
;WITH x as
(
SELECT e,c, MAX(CASE WHEN E = 'u1' THEN c END) OVER () newc
FROM tb1
)
UPDATE x
SET c = newc
WHERE e <> 'u1'