6

My Table is:

|ID |data | cr |
| 1 | AAA |    |
| 2 | AAA |    |
| 3 | AAA |    |
| 4 | BBB |    |
| 5 | CCC |    |
| 6 | BBB |    |

I need result:

|ID |data | cr |
| 1 | AAA | 3  |
| 2 | AAA | 3  |
| 3 | AAA | 3  |
| 4 | BBB | 2  |
| 5 | CCC | 1  |
| 6 | BBB | 2  |

Found this Update a column value to the COUNT of rows for specific values in same table and tried it:

UPDATE MyTbl a, 
        (SELECT data,COUNT(*) cnt 
            FROM MyTbl 
          GROUP BY data) b
    SET a.cr = b.cnt 
  WHERE a.data= b.data

SQL Server gives error :

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'a'.
Msg 102, Level 15, State 1, Line 4 Incorrect syntax near 'b'.

Any idea how to do this in SQL Server (2014 Express).

Thanks in advance.

Community
  • 1
  • 1
Kaptah
  • 9,785
  • 4
  • 22
  • 19

5 Answers5

5

It should be Update..set...from. Try this one:

update a
set a.cr=b.cnt
from MyTbl a join
     (SELECT data,COUNT(*) cnt 
            FROM MyTbl 
          GROUP BY data) b on a.data=b.data

Result:

ID  data    cr
--------------
1   AAA     3
2   AAA     3
3   AAA     3
4   BBB     2
5   CCC     1
6   BBB     2

Demo in SQL Fiddle

Raging Bull
  • 18,593
  • 13
  • 50
  • 55
2

Something like this

UPDATE t SET
    t.cr = vv.c
from MyTbl as t
left outer join 
(
    select count(*) as c , data from MyTbl group by data
) as vv on vv.data = t.data
Stefan Michev
  • 4,795
  • 3
  • 35
  • 30
2

You can use count with window function to find the count of each group. use this

;WITH cte
     AS (SELECT Count(1)OVER(partition BY data) AS crc,*
         FROM   MyTbl)
UPDATE cte
SET    cr = crc 

SQLFIDDLE DEMO

Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
1

Since you are using SQL server 2014 version, I'd recommend Windowed function used inside a self join update query type syntax.

update a
set a.cr= b.v
from
(select id, count(1) over(partition by data order by data) as v from myTbl) b
join 
myTbl a on a.ID=b.id
-- now see the result here
select * from MyTbl

Sql fiddle for demo http://sqlfiddle.com/#!6/bc02f/4

DhruvJoshi
  • 17,041
  • 6
  • 41
  • 60
0
;with x as
 (
  SELECT Data , COUNT(*) AS cr
  FROM Table 
  GROUP BY Data
 )
UPDATE t
 SET t.cr = x.cr
FROM x INNER JOIN Table t ON x.data = t.data
M.Ali
  • 67,945
  • 13
  • 101
  • 127