0

如何从 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

4 回答 4

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
于 2012-11-20T20:21:35.443 回答
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)
于 2012-11-20T20:19:22.160 回答
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
)
于 2012-11-20T20:17:37.690 回答
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";

在这里看到 sql-fiddle

于 2012-11-20T20:39:07.917 回答