sql - 在 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 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。
解决方案
您可以使用相关子查询。一种方法是:
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
anduser
是标识符的糟糕名称,因为它们与 SQL 关键字冲突。
推荐阅读
- azure-cosmosdb - Cosmos DB 使用 select 语句创建临时表
- jquery - 如何从 jquery 的 Select 元素中的选定选项中删除复选框元素
- android - Android : GridView 没有被标记为它加载到空 Activity
- python - 多处理比循环慢
- css - 无法在 Sass 中使用默认引导颜色
- ios - 错误域 = IDEProvisioningErrorDomain 代码 = 9 - 需要应用程序组的配置文件
- kubernetes - 使用 root 用户挂载到 kubernetes pod 时权限被拒绝
- php - 警告:PHP 启动:无法加载动态库“openssl”
- ruby-on-rails - 从另一台设备观看本地网络上的 puma 输出
- python - 如何遍历基因/ URL 列表并生成基因信息行?