-1

In my users table I need to calculate count of users by username length. For example:

  • 200 users has name 1 char length
  • 500 users has name 2 chars length
  • 1500 users has name 3 chars length
  • ...

I created MSSQL query:

SELECT 
  TOP 1000
  LEN(nick) as 'title',
  Count(*)
FROM [userstable]
WITH(NOLOCK)
GROUP BY title

After I run it I see next problem:

column 'userstable.Nick' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Could someone explain why?

1
  • You can't use the alias name in the group by Commented Oct 2, 2017 at 14:34

1 Answer 1

4

Group by is logically processed before Select so you cannot use alias there

SELECT TOP 1000 Len(nick) AS 'title',
                Count(*)
FROM   [userstable] WITH(NOLOCK)
GROUP  BY Len(nick) 

Also read this article to know about NOLOCK Bad habits : Putting NOLOCK everywhere

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.