在聚合函数中查找最大值

时间:2018-11-15 13:42:44

标签: sql sql-server tsql aggregate having

我有以下查询

USE Movies;

SELECT
    c.CountryName
    ,d.DirectorName
    ,f.FilmRunTimeMinutes AS [TotalRunTime]
FROM
    tblFilm as f
    JOIN tblCountry as c on c.CountryID = f.FilmCountryID
    JOIN tblDirector as d on d.DirectorID = f.FilmDirectorID
ORDER BY
    DirectorName

这给了我以下结果:

enter image description here

到目前为止一切都很好。

然后我将结果分组,以汇总每个主管和国家/地区的TotalRunTime:

SELECT
    c.CountryName
    ,d.DirectorName
    ,SUM(CONVERT(DECIMAL, f.FilmRunTimeMinutes)) AS [TotalRunTime]
    ,COUNT(*)
FROM
    tblFilm as f
    JOIN tblCountry as c on c.CountryID = f.FilmCountryID
    JOIN tblDirector as d on d.DirectorID = f.FilmDirectorID
GROUP BY
    CountryName
    ,DirectorName

这给了我以下结果:

enter image description here

现在,我想要具有最高Count(*)的演员(colum'no column name'),我尝试了此操作:

SELECT
    c.CountryName
    ,d.DirectorName
    ,SUM(CONVERT(DECIMAL, f.FilmRunTimeMinutes)) AS [TotalRunTime]
    ,COUNT(*)
FROM
    tblFilm as f
    JOIN tblCountry as c on c.CountryID = f.FilmCountryID
    JOIN tblDirector as d on d.DirectorID = f.FilmDirectorID
GROUP BY
    CountryName
    ,DirectorName
HAVING
    COUNT(*) = MAX(Count(*))

但是它不起作用:(。您能解释一下为什么它不能详细工作以及如何用max(count(*))获得行吗?在此示例中,它应该给我日本排| Akira usw。

1 个答案:

答案 0 :(得分:0)

只需使用TOP (1)子句:

SELECT TOP (1) c.CountryName, d.DirectorName,
       SUM(CONVERT(DECIMAL, f.FilmRunTimeMinutes)) AS [TotalRunTime]
       COUNT(*) AS cnt
FROM tblFilm as f JOIN 
     tblCountry as c 
     on c.CountryID = f.FilmCountryID JOIN 
     tblDirector as d 
     on d.DirectorID = f.FilmDirectorID
GROUP BY CountryName, DirectorName
ORDER BY cnt DESC;

但是,如果cnt有联系,则可能失败,然后使用RANK()

SELECT t.*
FROM (SELECT c.CountryName, d.DirectorName,
             SUM(CONVERT(DECIMAL, f.FilmRunTimeMinutes)) AS [TotalRunTime]
             COUNT(*) AS cnt,
             RANK() OVER (ORDER BY COUNT(*) DESC) AS Seq
      FROM tblFilm as f JOIN 
           tblCountry as c 
           ON c.CountryID = f.FilmCountryID JOIN 
           tblDirector as d 
           ON d.DirectorID = f.FilmDirectorID
      GROUP BY CountryName, DirectorName
    ) t
WHERE seq = 1;