我正在尝试创建一个查询,该查询返回另一个表中最大次数的一个东西的名称和国家/地区。
这是结构:
ShipModels(mname, type, country, numGuns, gunSize)
Ships(sname, hasModel, launchYear)
Battles(bname, year)
Outcomes(ship, battle, result)
我尝试过很多不同的东西,但无法让它发挥作用。这是我目前的查询:
SELECT ship, country
FROM ShipModels, Ships, Outcomes
WHERE hasModel = mname AND ship = sname
GROUP BY ship
HAVING COUNT(ship) >=
( SELECT COUNT (ship) FROM Outcomes GROUP BY ship);
Oracle错误:
ERROR at line 1:
ORA-00979: not a GROUP BY expression
从我读过的内容中,当SELECT语句中存在聚合函数时会抛出此错误,但是......好吧,没有。有什么我想念的吗?我怎样才能让它发挥作用?
答案 0 :(得分:2)
您将country
包含在SELECT
:
SELECT ship, country
但不在GROUP BY
。将该行更改为:
GROUP BY ship, country
当你纠正它时,你会遇到另一个错误,因为子查询不是标量,例如不会返回单个值:
( SELECT COUNT (ship) FROM Outcomes GROUP BY ship)
你可能想写:
( SELECT MAX(cnt)
FROM
( SELECT COUNT(ship) AS cnt FROM Outcomes GROUP BY ship ) t
)
因此,完整查询将或多或少:
SELECT ship, country
FROM ShipModels, Ships, Outcomes
WHERE hasModel = mname AND ship = sname
GROUP BY ship, country
HAVING COUNT(ship) =
( SELECT MAX(cnt)
FROM
( SELECT COUNT(ship) AS cnt FROM Outcomes GROUP BY ship ) t
) ;
您还可以使用关键字ALL
:
SELECT ship, country
FROM ShipModels, Ships, Outcomes
WHERE hasModel = mname AND ship = sname
GROUP BY ship, country
HAVING COUNT(ship) >= ALL
( SELECT COUNT(ship) AS cnt FROM Outcomes GROUP BY ship ) ;
如果使用显式连接的“现代”(SQL-92)语法也会很好。而不是:
FROM ShipModels, Ships, Outcomes
WHERE hasModel = mname AND ship = sname
最好有各种理由写:
FROM ShipModels m
JOIN Ships s ON s.hasModel = m.mname
JOIN Outcomes o ON o.ship = s.sname
答案 1 :(得分:0)
问题在于HAVING子句中的count(ship)。我认为这是select语句中的聚合函数。