Select only largest values in a SQL relation?

橙三吉。 提交于 2020-01-02 09:13:47

问题


I have the following two relations:

Game(id, name, year)
Devs(pid, gid, role)

Where Game.id is a primary key, and where Devs.gid is a foreign key to Game.id.

I want to write a SQL query that finds the game with the largest amount of people who worked on that game. I wrote the following query:

SELECT Game.name, count(DISTINCT Devs.pid)
FROM Game, Devs
WHERE Devs.gid=Game.id
GROUP BY Devs.gid, Game.name
ORDER BY count(Devs.pid) DESC;      

This query sort of accomplishes my goal, in the sense that it returns all of the Games in the relation sorted by the number of people who worked on each game, but I'm trying to modify this query so that it does two things. One, it should only return the game with the most people who worked on it, and two, if there are two games that had an equal amount of people work on them, it should return both of those games. I know that if I replace the top line like so:

SELECT TOP 1 Game.name, count(DISTINCT Devs.pid)

Then it accomplishes my first goal, but if there are two games that both have the highest number of people who worked on them, then it only returns one of those games. How can I go about changing this query so that it will return all games with the highest number of people that worked on it?


回答1:


The task can be shorten to:

Give me all the rows from the original query with the maximum number of developers

It can be reached through the WITH statement. The answer is the following:

WITH GamesDevs (GameName, DevsCount)
AS
(
    SELECT Game.name AS GameName, count(DISTINCT Devs.pid) AS DevsCount
    FROM Game, Devs
    WHERE Devs.gid=Game.id
    GROUP BY Devs.gid, Game.name
    ORDER BY count(Devs.pid) DESC 
)

SELECT * FROM GamesDevs WHERE GamesDevs.DevsCount = (SELECT MAX(DevsCount) FROM GamesDevs)

Hope this helps.




回答2:


This should also work :)

SELECT Game.name, count(DISTINCT Devs.pid)
FROM Game, Devs
WHERE Devs.gid=Game.id
GROUP BY Devs.gid, Game.name
Having count(DISTINCT Devs.pid) = Max(count(DISTINCT Devs.pid))
ORDER BY count(Devs.pid) DESC;  



回答3:


Try this query :

  select g.name, count(d.gid)
  from 
  game g 
    join 
  devs d 
  on g.id=d.gid
  group by g.name 
  having count(d.gid)= (select max (temp.cnt) from 
      (select gid p, count(*) cnt 
       from devs 
       group by gid) temp)
  ;



回答4:


Just use with ties syntax, if that's the only thing that isn't working:

https://msdn.microsoft.com/en-us/library/ms189463.aspx

select      top 1 with ties
            game.name,
            count(distinct devs.pid)
from        game
       join devs
         on devs.gid = game.id
group by    devs.gid,
            game.name
order by    3 desc

Also consider modern join syntax.



来源:https://stackoverflow.com/questions/29787954/select-only-largest-values-in-a-sql-relation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!