查找客户来自的城市总数。为什么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