为什么这个SQL查询不能在Northwind数据库上运行?

时间:2015-12-18 20:35:04

标签: sql sql-server

查找客户来自的城市总数。

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

错误:

  

错误第4行:')'..

附近的语法不正确

解释是什么?

2 个答案:

答案 0 :(得分: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

     

当派生表,行集或表值函数或运算符时   使用了子句(例如PIVOT或UNPIVOT),所需的table_alias at   子句的结尾是所有列的关联表名,   包括分组列,返回。

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;

答案 1 :(得分:2)

使用子查询时需要指定别名:

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

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

select count(distinct city)
from 
customers;