如何在SQL Server中使用SELECT语句的结果更新表

5

我想更新一个表,其中字段的值等于选择语句的结果。我的表如下:

Type     Total#
A           4
B           8
C           1

我希望根据一个select语句的结果来更新上述表格。 以下是我的代码:
update MainTable
  set [Total#] = 
  (SELECT count(distinct r.[ID])as Type
  FROM dbo.TableA r left join
  dbo.TableB a
  on r.Post_ID = a.Post_ID
  where a.Status is null)

如果我按原样运行代码,它将更新所有行,但我只想更新选择语句中的 Type 等于 MainTable 中的 Type 的行。谢谢。

表A和表B的表结构是什么? - John Woo
2个回答

9

请尝试一下这个:

UPDATE  x
SET     x.[Total#] = y.totalCount
FROM    MainTable x
        INNER JOIN
        (
            SELECT  [Type], COUNT(DISTINCT r.[ID]) totalCount
            FROM    dbo.TableA r
                    LEFT JOIN dbo.TableB a
                        ON r.Post_ID = a.Post_ID
            WHERE   a.STATUS IS NULL
            GROUP BY    [Type]
        ) y ON x.[Type] = y.[Type]

提示:当提出这样的问题时,请添加表格结构。这将非常有帮助。


0

给你的 MainTable 取一个别名,然后你就可以在子查询中使用它:

update MainTable mt
   set [Total#] = (SELECT count(distinct r.[ID]) as Type
                     FROM dbo.TableA r 
                          left join dbo.TableB a on r.Post_ID = a.Post_ID
                    where a.Status is null
                      and a.AType = mt.AType )
 where mt.AType = @Value

谢谢,但是我遇到了一个错误:必须声明标量变量“@Value”。 - moe
@moe 所示查询是一个例子,如果你不需要where,可以将其删除或将@value调整为你想要过滤的实际值。 - jachguate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接