2015-12-18 110 views

回答

3

根据你前面的问题我假设你使用Oracle哪里你可以写:

SELECT * 
FROM (SELECT 1 FROM dual) 

但不是:

SELECT * 
FROM (SELECT 1 FROM dual) AS s 
-- ORA-00933: SQL command not properly ended 

SQL Server你需要添加别名子查询:

select count(*) from (select distinct city from customers) AS s; 

FROM clause

[AS] table_alias

When a derived table, rowset or table-valued function, or operator clause (such as PIVOT or UNPIVOT) is used, the required table_alias at the end of the clause is the associated table name for all columns, including grouping columns, returned.

SQL Server力,您可以添加别名列表达和汇总列:

SELECT * 
FROM (SELECT 1) AS s 
-- No column name was specified for column 1 of 's'. 

你需要使用:

SELECT * 
FROM (SELECT 1) AS s(c) 

SELECT * 
FROM (SELECT 1 AS c) AS s 


个人我不是子查询的球迷,我更喜欢公用表表达式语法:

;WITH cte(city) AS 
(
    SELECT DISTINCT city 
    FROM customers 
) 
SELECT COUNT(*) AS no_of_cities 
FROM cte; 

当然对于这样便于查询的最好方法是增加DISTINCT直接COUNT

SELECT COUNT(DISTINCT city) AS no_of_cities 
FROM customers; 
2

您需要分配一个别名使用子查询时:

select count(*) 
from 
(select distinct city 
from customers) as MyTable; 

或者只是跳过子查询,在这个例子:

select count(distinct city) 
from 
customers; 
相关问题