仅选择SQL关系中的最大值?

编程入门 行业动态 更新时间:2024-10-09 23:22:04
本文介绍了仅选择SQL关系中的最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下两个关系:

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

其中Game.id是主键,而Devs.gid是Game.id的外键.

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

我想编写一个SQL查询,以查找从事该游戏工作的人员最多的游戏.我写了以下查询:

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?

推荐答案

任务可以简化为:

给我原始查询中所有具有最大开发人员数量的行

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

可以通过WITH 声明进行访问.答案如下:

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)

希望这会有所帮助.

更多推荐

仅选择SQL关系中的最大值?

本文发布于:2023-10-28 10:40:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536404.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最大值   关系   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!