1

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

4 に答える 4

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
于 2012-10-08T13:01:23.500 に答える
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;

これがライブデモです

于 2012-10-08T12:59:09.063 に答える
0

ここで更新マニュアルを参照できます:

;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);
于 2012-10-08T12:59:29.437 に答える
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
于 2012-10-08T13:55:33.340 に答える