如何从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)
答案 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";