用WHERE替换HAVING

时间:2013-04-17 06:06:59

标签: sql oracle where having

SELECT team, sum(maths)
FROM marks
GROUP BY team
HAVING sum(maths) = (
    SELECT max(sum(maths))
    FROM marks
    GROUP BY team
)

有三支队伍A,B,C,其中一些队员没有。

首先使用SELECT max(sum(maths)) FROM marks GROUP BY team我获得了数学的最大总和。

现在使用整个查询我试图显示数学总和最高的团队。

如何重写查询以将HAVING替换为WHERE

5 个答案:

答案 0 :(得分:1)

请尝试:

select * from (
  select team, v maxmarks, row_number() over (order by v desc) RNum from(
    SELECT team, sum(maths) v
    FROM marks 
    group by team 
  )x
)xx where RNum=1;

答案 1 :(得分:0)

可以将HAVING替换为WHERE,但这样做没有任何好处。

select team, sum(maths) from
(
   SELECT team, sum(maths) as total
   FROM marks
   GROUP BY team
) t1
where t1.total = ( select max(t1.total) from t1 )

答案 2 :(得分:0)

如果您订购了结果,可以使用ROWNUM pseudocolumn将它们包裹在外部SELECT中,将其限制在第一行:

SELECT *
FROM (
    SELECT team, sum(maths)
    FROM marks
    GROUP BY team
    ORDER BY sum(maths) DESC
)
WHERE ROWNUM = 1;

或者您可以使用ROW_NUMBER analytic function,再次包装在外部选择中:

SELECT *
FROM (
    SELECT team, sum(maths),
        ROW_NUMBER() OVER (PARTITION BY team ORDER BY sum(maths) DESC) AS rn
    FROM marks
    GROUP BY team
)
WHERE rn = 1;

答案 3 :(得分:0)

它并不比其他人更有效,但如果你只是想要多种方式,你可以试试这个。

SELECT DISTINCT FIRST_VALUE(TEAM) OVER(ORDER BY SUM(MATHS) DESC),
          FIRST_VALUE(SUM(MATHS)) OVER(ORDER BY SUM(MATHS) DESC)
FROM MARKS
GROUP BY TEAM

答案 4 :(得分:0)

另一种方法,使用公用表表达式:

with team_sum as (
  select   team,
           sum(maths) sum_maths
  from     marks
  group by team)
select *
from   team_sum
where  sum_maths = (
         select max(sum_maths)
         from   team_sum)

对于非常多的团队而言,它会表现良好,因为优化器可以实现team_sum公用表表达式的结果集并对其执行max()。

它还列出了多个团队,他们共享相同的总分。