2015-12-18 112 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; 
相關問題