简体   繁体   English

在SQL中查找两个嵌套聚合函数的最大值

[英]Finding Max of two nested aggregate functions in SQL

I have an MS Access 2007 Database with the following tables and attributes: 我有一个具有以下表和属性的MS Access 2007数据库:

  • Characters: Name 字符:姓名
  • Planets: Name 行星名称
  • TimeTable: Planet's Name, Character's Name 时间表:行星名称,角色名称

Time Table denotes if a character has visited a planet, there may be multiple entries for one planet. 时间表表示角色是否已访问过行星,一个行星可能有多个条目。
The query I'm trying to get is this one: 我试图得到的查询是这个:
For each movie, which characters visited the highest number of planets? 对于每部电影,哪个角色访问的行星数量最多?

This is my attempt: 这是我的尝试:

SELECT T.Movie, T.[Character's Name], Count(T.[Planet's Name]) AS planets
FROM TimeTable T
GROUP BY T.Movie, T.[Character's Name]
HAVING Count(T.[Planet's Name]) >= ALL (SELECT Count(T2.[Planet's Name])
FROM TimeTable T2 WHERE T.Movie = T2.Movie);

It gives me an empty result though. 它给了我一个空的结果。 What is wrong with my query? 我的查询出了什么问题?

You have asked for the row that is greater or equal to all rows. 您要求的行大于或等于所有行。 The query below will return matches, that is, all rows with the same highest value will be returned. 下面的查询将返回匹配项,即,将返回所有具有相同最大值的行。

SELECT t.movie,
       t.character,
       Count(t.planet) AS CountOfPlanet
FROM   timetable t
GROUP  BY t.movie, t.character
HAVING Count(t.planet) = (
   SELECT Max(countofplanet)
   FROM   (
   SELECT movie,
          [character],
          Count(planet) AS CountOfPlanet
          FROM   timetable
          GROUP  BY movie, [character]) q
   WHERE  q.movie = t.movie) 

I am afraid I could not cope with your field names. 恐怕我无法应付您的字段名称。 I might have overlooked the spaces, but the apostrophe's were just going too far. 我可能忽略了空格,但是撇号的位置太远了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM