techV
techV

Reputation: 935

Select Query using Column Alias Name

I have a query like :

Select table1.Name AS aliasname1, Count(aliasname1) as aliasname2 from table1.

But i am not sure if this query will execute successfully in sql because i have used alias name in same select statement .I need a solution for doing the same in sql. I want solution as

aliasname1   aliasname2

Name1         4
Name2         4
Name3         4
Name4         4

Upvotes: 0

Views: 2062

Answers (1)

Taryn
Taryn

Reputation: 247870

You can't reference an alias in your SELECT statement like that. You are creating and attempting to call an alias at the same time, so the compiler doesn't know what the aliasname1 is when you reference it in the same select statement. So in order to fix this, you'd have to write the query the following way:

select 
  table1.Name AS aliasname1, 
  Count(table1.Name) as aliasname2 
from table1

Or if you want to reference an alias, you'll need to use a subquery:

select aliasname1,
  count(aliasname1) as aliasname2 
from 
(
  select table1.Name AS aliasname1
  from table1
) as d

Upvotes: 2

Related Questions