无效的标识符错误,Oracle

时间:2015-09-28 09:42:35

标签: sql database oracle

我一直在尝试将此查询写入1小时,但SQL Developer总是会抛出错误。

SELECT d.driver_name, COUNT(*) AS cnt
  FROM Drivers d
  JOIN Fastest_laps fl ON d.ID_driver = fl.ID_driver
  GROUP BY d.driver_name
  HAVING cnt = MAX(cnt);
  
      
  1. 00000 - "%s:无效的标识符"
  2.         

    最后一行第20栏出错。

所以我找到了另一个解决方案,但又抛出了另一个错误:

SELECT d.driver_name, COUNT(*) as cnt
  FROM Drivers d
  JOIN Fastest_laps fl ON d.ID_driver = fl.ID_driver
  GROUP BY d.driver_name
  HAVING COUNT(*) = MAX(COUNT(*));
  
      
  1. 00000 - "群组功能嵌套太深"
  2.         

    最后一行第25栏出错。

编辑:谢谢gyus,你很棒,几乎所有的回复都有效,但我必须选择一个......

4 个答案:

答案 0 :(得分:2)

使用窗口功能:

SELECT driver_name, cnt
FROM (SELECT d.driver_name, COUNT(*) AS cnt,
             MAX(COUNT(*)) OVER () as MAXcnt
      FROM Drivers d JOIN
           Fastest_laps fl
           ON d.ID_driver = fl.ID_driver
      GROUP BY d.driver_name
     ) d
WHERE cnt = MAXcnt;

您也可以使用RANK()DENSE_RANK()

来表达这一点
SELECT driver_name, cnt
FROM (SELECT d.driver_name, COUNT(*) AS cnt,
             RANK() OVER (ORDER BY COUNT(*) DESC) as seqnum
      FROM Drivers d JOIN
           Fastest_laps fl
           ON d.ID_driver = fl.ID_driver
      GROUP BY d.driver_name
     ) d
WHERE seqnum = 1;

这种方法的优点是,您可以使用ROW_NUMBER()代替并获得一行,即使多个驱动程序具有相同的最大值。

答案 1 :(得分:1)

试试这个。我按cnt按降序排序。然后选择它的顶行。您可以将查询编辑为rownum <=2以获取前2行,依此类推。

           with tbl1 as
           (SELECT d.driver_name as driver_name, COUNT(*) AS cnt
            FROM Drivers d
            JOIN Fastest_laps fl ON d.ID_driver = fl.ID_driver
            GROUP BY d.driver_name
            order by cnt desc
            )
            select driver_name,cnt from tbl1
            where cnt = (select cnt from tbl1 rownum=1)

答案 2 :(得分:1)

我不确定Oracle是否支持此功能,但请试一试:

SELECT d.driver_name, COUNT(*) as cnt
FROM Drivers d
  JOIN Fastest_laps fl ON d.ID_driver = fl.ID_driver
GROUP BY d.driver_name
ORDER BY cnt DESC
FETCH FIRST 1 ROW WITH TIES

或使用公用表表达式:

with cte as
(
SELECT d.driver_name as driver_name, COUNT(*) AS cnt
FROM Drivers d
  JOIN Fastest_laps fl ON d.ID_driver = fl.ID_driver
GROUP BY d.driver_name
)
select driver_name, cnt
from cte
where cnt = (select max(cnt) from cte)

答案 3 :(得分:1)

您必须将查询包装到内联视图中才能查询cnt

select *
from   (
         SELECT d.driver_name, COUNT(*) AS cnt
         FROM Drivers d
         JOIN Fastest_laps fl ON d.ID_driver = fl.ID_driver
         GROUP BY d.driver_name
       ) x
group
by     driver_name, cnt
having cnt = MAX(cnt);