SQL Server UPDATE来自另一个表的多行值

时间:2012-10-08 12:55:33

标签: sql sql-server-2008

我有一个包含Id和Rcount的表。我需要更新每个成员的Rcount。像这样的东西

Id| Rby| Rcount
1 | 0  | 0
2 | 1  | 0
3 | 1  | 0
4 | 3  | 0
5 | 4  | 0
6 | 4  | 0
7 | 4  | 0
8 | 7  | 0

我使用

获取值
SELECT Rby, COUNT(Rby) FROM member GROUP BY Rby;

Rby| COUNT(Rby)
0  | 1
1  | 2
3  | 1
4  | 3
7  | 1

如何将结果更新为Rcount列?

4 个答案:

答案 0 :(得分:1)

UPDATE TableName 
SET Rcount = a.Cnt
FROM TableName t
INNER JOIN (SELECT Rby, COUNT(Rby) Cnt FROM member GROUP BY Rby) a ON a.Rby= t.Rby

答案 1 :(得分:0)

试试这个:

UPDATE m1
SET m1.Rcount = m2.RbyCount
FROM member m1
INNER JOIN
(
   SELECT Rby, COUNT(Rby) RbyCount
   FROM member 
   GROUP BY Rby
) m2 ON m1.Rby = m2.Rby
INNER JOIN member m3 ON m1.Id = m3.Id;

Here is a live demo

答案 2 :(得分:0)

您可以咨询update manual here

;with Table2 as (
  SELECT Rby, COUNT(Rby) as n FROM member GROUP BY Rby
)
UPDATE member 
SET member.Rby = Table2.n
FROM Table2 
    INNER JOIN dbo.Table1 
    ON (Table2.Rby = member.Rby);

答案 3 :(得分:0)

这是一个看起来有点不同的答案,但它运作良好

declare @table table(Id int, Rby int, Rcount int)

insert @table values(1,0,0),(2,1,0),(3,1,0),(4,3,0),(5,4,0),(6,4,0),(7,4,0),(8,7,0)

;with a as
(
select  id, rby, Rcount, count(*) over(partition by rby) new_rcount 
from @table
)
update a set Rcount= new_rcount
where coalesce(Rcount) <> new_rcount


select * from @table

结果:

Id  Rby Rcount
1   0   1
2   1   2
3   1   2
4   3   1
5   4   3
6   4   3
7   4   3
8   7   1