将列更新为另一列中特定值的COUNT行。 SQL Server

时间:2015-08-18 12:09:08

标签: sql-server

我的表是:

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

我需要结果:

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

找到此Update a column value to the COUNT of rows for specific values in same table并尝试了它:

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出错:

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

知道如何在SQL Server(2014 Express)中执行此操作。

提前致谢。

5 个答案:

答案 0 :(得分:5)

应该是Update..set...from。试试这个:

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

结果:

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

SQL Fiddle

中的演示

答案 1 :(得分:2)

像这样的东西

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

答案 2 :(得分:2)

您可以countwindow function一起使用来查找每个组的计数。使用这个

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

SQLFIDDLE DEMO

答案 3 :(得分:1)

由于您使用的是SQL Server 2014版本,因此我建议在自联接更新查询类型语法中使用Windowed函数。

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 for demo http://sqlfiddle.com/#!6/bc02f/4

答案 4 :(得分: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