简体   繁体   English

别名字段 列名无效

[英]alias fields Invalid column name

getting this error Invalid column name 'ALIAS1'收到此错误 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!在评论中发布查询...谢谢!

If you are using SQLServer then the problem is not only your alias, it is substracting two columns with date type.如果您使用的是SQLServer ,那么问题不仅在于您的别名,还在于减去两列日期类型。 Also using the alias created in the same select is not ok.也不能使用在同一个 select 中创建的别名。 Also if you are using T.firstdate expression then you should add capital T after the table name.此外,如果您使用 T.firstdate 表达式,则应在表名后添加大写 T。

In my DEMO在我的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)可以看到两个日期相减会报错(我的DEMO中的query 1和query2和query 3)
  2. You can also see what will happend if you do not use table alias T (query 4 from my DEMO)您还可以看到如果不使用表别名 T 会发生什么(来自我的 DEMO 的查询 4)
  3. And you can see what will happend if you use alias in the select you have created it (query 5 from my DEMO)您可以看到如果您在创建它的 select 中使用别名会发生什么(来自我的 DEMO 的查询 5)

I believe this is what you need if you are using SQL Server:如果您使用的是 SQL 服务器,我相信这就是您所需要的:

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 .这是该正确示例的演示: DEMO

If you are using ORACLE then the first query will be ok like in this DEMO如果您使用的是ORACLE ,那么第一个查询就可以了,就像在这个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 .所以,你看,我们需要知道你使用什么数据库 :) :)

inline alias is not allow all dbms内联别名不允许所有 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

It seem you are working with SQL server if so, then you can use apply to avoid repeat same expression:如果是这样,您似乎正在使用SQL server ,那么您可以使用apply来避免重复相同的表达式:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM