0

I have this Select statement

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

and a variable to calculate how many users from the department

@UserCounter

Is there a way to add count(the number of users from the department) into @UserCounter from the select statement should the statement runs in a while loop?

1
  • 1
    Provide DBMS version tag. Later versions of sql-server have handy windowing functions . Commented Jul 4, 2017 at 7:50

1 Answer 1

1

Presuming sql-server:

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

Otherwise a simple sub-query should work too:

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

The database should be clever enough to optimize that query so that the subquery doesn't need to be avaulated for every (matching) row.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Thanks for the reply! Is it going to be the same when you do UserCounter = UserCounter + (Count(*) OVER (Partition By Department)) inside the select statement?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.