SQL按部门分组选择最大项目数。

huangapple go评论50阅读模式
英文:

SQL select max items by grouping on department

问题

我有一个名为mytable的表,其中包含name,department,rating

示例:

a, d1, 3
b, d1, 5
c, d1, 10
a1, d2, 4
a2, d2, 1
a3, d2, 5

我希望输出按部门分组,并选择评分最高的一个,显示如下:

c, d1, 10
a3, d2, 5

我尝试过如下:

select name, department, max(rating) from mytab
group by department. 

但这个查询是错误的,因为我需要将name也添加到group by子句中。解决这个问题的正确方法是什么。

英文:

I have a table mytable with name, department, rating

example:

a, d1, 3
b, d1, 5
c, d1, 10
a1, d2, 4
a2, d2, 1
a3, d2, 5

I want the output to group the output by department and pick the one with highest rating and display like this:

c, d1, 10
a3, d2, 5

I tried like this:

select name, department, max(rating) from mytab
group by department. 

But this query is wrong as I need to add name also to group by clause. What is the right way to solve this.

答案1

得分: 1

这将为您提供在一个部门内具有最高评分的所有记录,因此如果有两个具有最高评分的记录,您将看到它们。

在子查询中,您会获得每个部门的最大值,然后只需选择具有该值的所有记录

select mytable.*
FROM  mytable
   JOIN (SELECT department, MAX(rating) AS rating 
         FROM mytable 
         GROUP BY department) maxvals
   USING (department, rating)
英文:

This will give you all the records with max rating within a department, so if two have the max rating, you will see both.

In the subquery you get the max values per department and then you just select all records with that value

select mytable.*
FROM  mytable
   JOIN (SELECT department, MAX(rating) AS rating 
         FROM mytable 
         GROUP BY department) maxvals
   USING (department, rating)

huangapple
  • 本文由 发表于 2023年7月7日 01:40:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76631316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定