查找客戶來自的城市總數。爲什麼SQL查詢不能在Northwind數據庫上工作?
select count(*)
from
(select distinct city
from customers);
錯誤:
Error line 4: Incorrect syntax near ')'..
有什麼解釋?
查找客戶來自的城市總數。爲什麼SQL查詢不能在Northwind數據庫上工作?
select count(*)
from
(select distinct city
from customers);
錯誤:
Error line 4: Incorrect syntax near ')'..
有什麼解釋?
根據你前面的問題我假設你使用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;
[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;
您需要分配一個別名使用子查詢時:
select count(*)
from
(select distinct city
from customers) as MyTable;
或者只是跳過子查詢,在這個例子:
select count(distinct city)
from
customers;
您需要添加別名子查詢'SELECT COUNT(*) 來回m (選擇來自客戶的不同城市 )AS s;' – lad2025