1
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.

4

5 回答 5

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;
于 2013-04-17T06:30:42.220 回答
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()。

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

于 2013-04-17T08:26:06.150 回答
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
于 2013-04-17T06:51:19.117 回答
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 )
于 2013-04-17T06:20:17.030 回答
0

如果您对结果进行排序,则可以使用SELECT列将它们包装在将其限制在第一行的外部:ROWNUM

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

或者您可以使用ROW_NUMBER分析函数,再次包装在外部选择中:

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;
于 2013-04-17T06:36:43.950 回答