MS SQL变量在同一语句中从count添加值

时间:2017-07-04 07:45:46

标签: sql-server tsql

我有这个Select语句

select Id, UserName, from UserTable where Department= @DepartmentInput

和一个变量来计算部门用户的数量

@UserCounter

如果语句在while循环中运行,是否可以通过select语句将count(来自部门的用户数)添加到@UserCounter中?

1 个答案:

答案 0 :(得分:1)

假设sql-server:

select Id, UserName, @UserCounter = Count(*) OVER (Partition By Department)
from UserTable 
where Department= @DepartmentInput

否则一个简单的子查询也应该起作用:

select Id, UserName, @UserCounter = (select count(*) from UserTable
                                     where Department= @DepartmentInput)
from UserTable 
where Department= @DepartmentInput

数据库应该足够聪明以优化该查询,以便不需要为每个(匹配)行设置子查询。