2012-11-21 186 views
4

我想更新一个tabel字段的值等于select语句的结果的tabel。我有这样一个表:如何使用SQL Server中的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类型。感谢

+0

tableA和tableB的表结构是什么? –

回答

8

试试这个,

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:问问题,这样的时候,请添加表格的结构。它有很多帮助。

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 
+0

谢谢,但我得到这个错误:必须声明标量变量“@Value”。 – moe

+0

@moe显示的查询是一个例子,如果您不需要where,删除它或将'@ value'调整为您要过滤的实际值。 – jachguate

相关问题