我试图将列设置为等于表中值发生的次数,但是当我尝试将其存储为列时遇到问题。我错过了什么?
目标
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。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。
答案 0 :(得分:1)
您可以使用相关子查询。一种方法是:
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;
注意:count
和user
是标识符的糟糕名称,因为它们与SQL关键字冲突。
答案 1 :(得分:0)
update [User] u1
set [count] = (select count(*)
from [User] u2
where u1.col1 = u2.col1)
答案 2 :(得分:0)
我通常会通过创建一个FROM
子句来计算我想要的数据,然后将其重新连接到原始表中。
UPDATE [user]
SET [count] = repidck
FROM
[user]
INNER JOIN
(
SELECT col1, COUNT(*) repidck
FROM [user]
GROUP BY col1
) counts
ON counts.col1 = [user].col1
希望这有帮助