SQL查询-子查询计数
我想获取查询中检索到的所有列的计数。我使用了以下代码:SQL查询-子查询计数,sql,sql-server-2008,count,subquery,Sql,Sql Server 2008,Count,Subquery,我想获取查询中检索到的所有列的计数。我使用了以下代码: select count (*) from ( select distinct ID,salary,name,location from test ) ; 我收到一条错误消息: 不正确的错误;应为、ID或引用的\u ID 当我添加如下内容时: select count (*) from ( select distinct ID,salary,name,location from test ) as c
select count (*)
from (
select distinct ID,salary,name,location
from test
) ;
我收到一条错误消息:
不正确的错误;应为、ID或引用的\u ID
当我添加如下内容时:
select count (*)
from (
select distinct ID,salary,name,location
from test
) as count;
查询现在可以工作,但列名未重命名为给定的别名。这背后的逻辑是什么?在Sql中,必须为子查询指定别名。这就是为什么第二个查询有效,而第一个查询失败的原因,我不知道您想要实现什么,但要纠正这一点,需要
select count (*) from (select distinct ID,salary,name,location from test ) as myTAble;
子查询将充当要查询的表,因此它需要一个
姓名或别名
您正在为表而不是列指定别名。下面的查询将起作用
select count (*) As count
from (
select distinct ID,salary,name,location
from test
) as tbl;
有些DBMS要求派生表有别名,有些则没有。您使用的是哪种DBMS?我使用的是Microsoft SQL Server 08,我担心的是,即使在指定别名后,列名也不会更改,它将显示为无列名。您为派生表指定了别名,而不是列。如果要为列指定别名,必须在此处指定,count*as count from。。。现在这很有意义。谢谢,应该在应该重命名的列后面使用带有\u no\u name的\u horse\u别名,该列位于from之前。无论如何,在这段代码中,显示的列名不带别名。要正式将其放入派生表,据我所知,第二个查询可以工作,但列名没有使用查询中给定的别名重命名,它显示为无列名