SQL Server语言
在northwind数据库中,找到向其报告的人数最多的经理。我写了一个问题:SQL Server语言,sql,sql-server,Sql,Sql Server,在northwind数据库中,找到向其报告的人数最多的经理。我写了一个问题: Select reportsto from (select top 1 reportsto, count(reportsto)from employees group by reportsto order by count(reportsto) desc) 但它给出了一个错误 “')附近的语法不正确 尝试在计数(reportsto)后添加空格 而不是 count(reportsto)fr
Select reportsto from
(select top 1 reportsto,
count(reportsto)from employees group by
reportsto order by count(reportsto) desc)
但它给出了一个错误
“')附近的语法不正确
尝试在
计数(reportsto)
后添加空格
而不是
count(reportsto)from
您可以使用下面的
SELECT *
FROM Employees
WHERE EmployeeID IN (SELECT TOP 1 WITH TIES ReportsTo
FROM Employees
GROUP BY ReportsTo
ORDER BY COUNT(ReportsTo) DESC)
WITH TIES
选项意味着,如果多个经理向他们报告的人数最多,您将获得所有经理的详细信息。这条不太清楚的消息意味着您需要在所述(最后一个)括号后加上别名。SQL Server要求必须为子选择指定别名。所以,应该是这样的:
Select reportsto from
(select top 1 reportsto,
count(reportsto)from employees group by
reportsto order by count(reportsto) desc) s /* 's' is just an example,
you can assign any alias */
也就是说,您只需从SELECT子句中删除
COUNT()
列,并按原样使用子查询的其余部分,结果将与您的原始意图相同。当然,除非有比我们能看到的更多的内容。在提问之前尝试进行一些基本的调试。我已经更改了空间,但我想知道谁是使用employee表中的查询的northwind数据库中的经理
Select reportsto from
(select top 1 reportsto,
count(reportsto)from employees group by
reportsto order by count(reportsto) desc) s /* 's' is just an example,
you can assign any alias */
select top 1 reportsto
from employees
group by reportsto
order by count(reportsto) desc