2014-09-22 32 views
-1

我想计数的结果赋值给一个变量,这样我就可以在随后的查询中使用它,这里是我的代码:为什么在这个查询中有无效的标识符?

select distinct(Artist), count(distinct(Instrument)) as allins 
from performers 
where allins = (select count(distinct(x.Instrument)) 
       from performers x) 
group by Artist; 

错误:ORA-00904: "ALLINS": invalid identifier

+3

[在WHERE子句中使用别名]可能的重复(http://stackoverflow.com/questions/356675/using-an-alias-in-a-where-clause) – 2014-09-22 00:07:35

回答

2

这是您的查询:

select distinct(Artist), count(distinct(Instrument)) as allins 
from performers 
where allins = (select count(distinct(x.Instrument)) from performers x) 
group by Artist; 

淘气,调皮。您不能使用在where子句中的select中定义的列别名。您也不能在where子句中使用聚合函数,所以代码没有意义。你想要的是一个having条款:

select Artist, count(distinct(Instrument)) as allins 
from performers 
group by Artist 
having count(distinct Instrument) = (select count(distinct x.Instrument) from performers x) 

注意:你几乎不必select distinct当你有一个聚集查询。而且,distinct不是一个函数,所以括号是不必要的。

0

SQL的执行与Java或C绝对不一样,所以经常会让新程序员进入语言。

更多的,往往不是数据库的理解SQL指令的顺序是这样的:

FROM - > WHERE - > GROUP BY - > - >选择

为了正确地做到这一点你不能在SELECT子句中声明某些东西是别名,并且期望它能够工作,因为程序很可能从FROM子句开始。

另外,根据我的经验,在SELECT子句中引用对方时,列别名不能很好地工作。

我相当不幸的解决方案就是不使用别名并输入整个事情。

另外,您绝对肯定地不应该在WHERE子句中使用聚合函数。它必须始终处于HAVING子句中。如果您不希望Oracle投诉要求艺术家,您还需要使用GROUP BY子句。此外,由于您正在按艺术家进行分组,而其他功能是聚合,因此您无需使用DISTINCT。

相关问题