如何从table2.rows更新table1.column值与SQL server中的where where一起计算

时间:2017-12-01 13:11:54

标签: sql sql-server

如何更新table2.rows中的table1.column值与SQL Server中的where where

1 个答案:

答案 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

对于将来的参考,如果您可以发布一些数据集和预期结果,它会有所帮助。现在,虽然这应该让你朝着正确的方向前进。