5

我正在尝试更新一个表,其中字段的值等于 select 语句的结果。我有一张这样的桌子:

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)

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

4

2 回答 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]

PS:问这样的问题时,请添加表格的结构。它有很大帮助。

于 2012-11-21T02:13:35.823 回答
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
于 2012-11-21T01:58:26.863 回答