如何从sql server中的select语句更新表

时间:2012-11-20 20:12:32

标签: sql sql-server-2008

如何从select语句结果更新表。这是我的选择声明:

SELECT count(distinct r.[ID])as Total
  FROM Table1 r left join
  Tabel2 a
  on r.ID = a.ID
  where a.Status is null

这就像我想做的那样,我知道这是错的:

update MyTable
set mycol = total
from
(
SELECT count(distinct r.[ID])as Total
      FROM Table1 r left join
      Tabel2 a
      on r.ID = a.ID
      where a.Status is null)

4 个答案:

答案 0 :(得分:1)

使用set中的子查询:

update MyTable
set mycol = (
  SELECT count(distinct r.[ID])
  FROM Table1 r left join
  Tabel2 a
  on r.ID = a.ID
  where a.Status is null
)

答案 1 :(得分:1)

你所要做的就是做一些微小的改变。以下是您需要使用的代码:

update MyTable
set mycol = (SELECT count(distinct r.[ID])as Total
  FROM Table1 r left join
  Tabel2 a
  on r.ID = a.ID
  where a.Status is null)

答案 2 :(得分:1)

如果我假设你在两个表中都有多行,并且想要逐行更新第一个表以及子查询中的相关结果,那么你需要添加一个连接(假设两个数据集将具有我在下面称为“识别字段”的内容:

Update MyTable
set mycol = b.total
from
MyTable a
inner join 
(
  SELECT identifyingfield, count(distinct r.[ID])
  FROM Table1 r left join
  Tabel2 a
  on r.ID = a.ID
  where a.Status is null
  group by identifyingfield
) b
ON a.identifyingfield = b.identifyingfield

答案 3 :(得分:1)

你可以尝试这样的事情:

with "sums"
as
(
  select 
    F."id"
  , "sum" = sum( F."value" ) over ( partition by F."id" )
  from
    "foo" F
)
update 
  B
set
  B."totals" = S."sum"
from
  "bar" B 
  inner join "sums" S
    on S."id" = B."id";

see sql-fiddle here