如何使用SQL Server中的where条件从table2.rows更新到table1.column值
Give this a go. See if it gives you enough to work with.
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
For future ref it helps if you can post some data sets and expected results. For now though this should get you going in the right direction.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.