首页 > 解决方案 > 在 T-SQL 中设置等于计数的列

问题描述

我正在尝试将列设置为等于值在表中出现的次数,但是当我尝试将其存储为列时遇到问题。我错过了什么?

目标

   id col1 count
  --------------
   1   a    3
   2   a    3
   3   a    3
   4   b    2
   5   b    2

我试过了:

select count(col1) as repidck 
from [User] u 
group by u.id

它本身可以工作,但是当我尝试设置一列时,我得到

update [User] 
set [count] = (select count(col1) as repidck 
               from [User] u 
               group by u.id)

错误:

子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。

标签: sqlsql-server

解决方案


您可以使用相关子查询。一种方法是:

update u
    set [count] = (select count(col1) from [User] u2 where u2.id = u.id)
    from [User] u;

但我可能会使用可更新的 CTE:

with toupdate as (
      select u.*, count(u.col1) over (partition by u.id) as new_count
      from [User] u
     )
update toupdate
    set [count] = new_count;

注意: countanduser是标识符的糟糕名称,因为它们与 SQL 关键字冲突。


推荐阅读