如何更新table2.rows中的table1.column值与SQL Server中的where where
答案 0 :(得分:1)
放手一搏。看看它是否足以让你使用。
DECLARE @TABLE1 AS TABLE (KeyField CHAR(1)
,CountField INT
)
DECLARE @TABLE2 AS TABLE (KeyField CHAR(1)
,OtherData NVARCHAR(MAX)
)
INSERT INTO @TABLE1
(KeyField, CountField)
VALUES ('A', 0)
, ('B', 0)
, ('C', 0)
INSERT INTO @TABLE2
(KeyField, OtherData)
VALUES ('A', CAST(NEWID() AS NVARCHAR(MAX)))
, ('A', CAST(NEWID() AS NVARCHAR(MAX)))
, ('B', CAST(NEWID() AS NVARCHAR(MAX)))
, ('B', CAST(NEWID() AS NVARCHAR(MAX)))
, ('B', CAST(NEWID() AS NVARCHAR(MAX)))
, ('C', CAST(NEWID() AS NVARCHAR(MAX)))
;
WITH cte
AS (SELECT KeyField
, COUNT(1) AS Cnt
FROM @TABLE2
GROUP BY KeyField
)
UPDATE T1
SET T1.CountField = T2.Cnt
FROM @TABLE1 T1
JOIN cte T2 ON T2.KeyField = T1.KeyField
SELECT * FROM @TABLE1
对于将来的参考,如果您可以发布一些数据集和预期结果,它会有所帮助。现在,虽然这应该让你朝着正确的方向前进。