pnetaly
pnetaly

Reputation: 67

alias fields Invalid column name

getting this error Invalid column name 'ALIAS1'

what can i do?

SELECT T.firsrdate, T.lastdate ,
T.lastdate - T.firsrdate as ALIAS1,
case when ALIAS1> 15 then 'a' else 'b' end as ALIAS2 FROM Table1

posted the query in comment... thank you!

Upvotes: 1

Views: 1479

Answers (3)

VBoka
VBoka

Reputation: 9083

If you are using SQLServer then the problem is not only your alias, it is substracting two columns with date type. Also using the alias created in the same select is not ok. Also if you are using T.firstdate expression then you should add capital T after the table name.

In my DEMO

  1. You can see that the substraction of two dates will give an error (query 1 and query2 and query 3 from my DEMO)
  2. You can also see what will happend if you do not use table alias T (query 4 from my DEMO)
  3. And you can see what will happend if you use alias in the select you have created it (query 5 from my DEMO)

I believe this is what you need if you are using SQL Server:

SELECT T.firstdate
       , T.lastdate 
       , datediff(day, T.firstdate , T.lastdate) as Alias1
       , case when (datediff(day, T.firstdate , T.lastdate )) > 15 
            then 'a' 
            else 'b' 
         end as Alias2
FROM Table1 T;

HEre is the demo for that correct example: DEMO.

If you are using ORACLE then the first query will be ok like in this DEMO

SELECT T.firstdate
       , T.lastdate 
       , (T.lastdate - T.firstdate) as ALIAS1
       , case when (T.lastdate - T.firstdate) > 15 then 'a' else 'b' end as ALIAS2 
FROM Table1 T;

So, you see, we need to know what database do you use. :)

Upvotes: 1

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

It seem you are working with SQL server if so, then you can use apply to avoid repeat same expression :

select t.firstdate, t.lastdate, tt.alias1,
       (case when alias1 > 15 then 'a' else 'b' end) as alias2
from table1 t cross apply
     ( values (t.lastdate - t.firstdate) 
     ) tt(alias1);

Upvotes: 0

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 32003

inline alias is not allow all dbms

 SELECT T.firsrdate, T.lastdate ,
T.lastdate - T.firsrdate as ALIAS1,
case when T.lastdate - T.firsrdate> 15 then 'a' else 'b' end as 
 ALIAS2 FROM Table1

Upvotes: 0

Related Questions