当我尝试解决这个问题时,我遇到了一个错误。首先,我需要计算 2 个表的所有值,然后我需要在条件中获取所有最大值。
我的代码:
Select *
FROM (
select Operator.OperatoriausPavadinimas,
(
select count(*)
from Plan
where Plan.operatoriausID= Operator.operatoriausID
) as NumberOFPlans
from Operator
)a
where a.NumberOFPlans= Max(a.NumberOFPlans)
我收到此错误
Msg 147,级别 15,状态 1,第 19 行 聚合不能出现在 WHERE 子句中,除非它位于 HAVING 子句或选择列表中包含的子查询中,并且要聚合的列是外部引用。
我不知道如何解决这个问题。
我需要得到这个 http://prntscr.com/p700w9
更新 1
计划表包含 http://prntscr.com/p7055l 值和 运算符表包含 http://prntscr.com/p705k0 值。
你在寻找...联接两个表并返回具有最大计数的记录的聚合查询?
我怀疑这可能是这样说的:
SELECT TOP(1) o.OperatoriausPavadinimas, COUNT(*)
FROM Operatorius o
INNER JOIN Planas p ON p.operatoriausID = o.operatoriausID
GROUP BY o.OperatoriausPavadinimas
ORDER BY COUNT(*) DESC
如果要允许领带,可以使用TOP(1) WITH TIES
.
您可以使用top with ties
. 您的查询有点难以理解,但我认为您想要:
select top (1) with ties o.OperatoriausPavadinimas, count(*)
from plan p join
operator o
on p.operatoriausID = o.operatoriausID
group by o.OperatoriausPavadinimas
order by count(*) desc;