SQL希望避免重复行
我有一张这样的桌子:SQL希望避免重复行,sql,database,postgresql,Sql,Database,Postgresql,我有一张这样的桌子: Employee | id | name | department | | 01 | Joe | Network | | 02 | Sam | Quality | | 03 | Mark | Network | | 04 | Pete | Quality | Hours | id | date | hours | | 01 | 1/1/11 | 7 | | 02 | 1/2/11 | 15 | | 03 | 1/5/11
Employee
| id | name | department |
| 01 | Joe | Network |
| 02 | Sam | Quality |
| 03 | Mark | Network |
| 04 | Pete | Quality |
Hours
| id | date | hours |
| 01 | 1/1/11 | 7 |
| 02 | 1/2/11 | 15 |
| 03 | 1/5/11 | 13 |
| 01 | 1/7/11 | 5 |
| 01 | 1/11/11 | 9 |
| 02 | 1/11/11 | 11 |
| 03 | 1/12/11 | 14 |
| 04 | 1/12/11 | 14 |
和其他类似的表格:
Employee
| id | name | department |
| 01 | Joe | Network |
| 02 | Sam | Quality |
| 03 | Mark | Network |
| 04 | Pete | Quality |
Hours
| id | date | hours |
| 01 | 1/1/11 | 7 |
| 02 | 1/2/11 | 15 |
| 03 | 1/5/11 | 13 |
| 01 | 1/7/11 | 5 |
| 01 | 1/11/11 | 9 |
| 02 | 1/11/11 | 11 |
| 03 | 1/12/11 | 14 |
| 04 | 1/12/11 | 14 |
我想查询:显示每个部门实现最大总小时数的人员(从最大到最小排序)
我当前的代码不起作用,只显示每个人的总小时数:
SELECT e.name, e.department, SUM(h.hours) AS total
FROM employee e JOIN hours h ON e.id = h.id
GROUP BY e.name, e.department
ORDER BY total DESC;
我需要做什么
我试过这样的东西
SELECT e.name, e.department, t.total
FROM (
SELECT e2.department, SUM(h.hours) AS total
FROM employee e2 JOIN hours h ON e2.id=h.id
GROUP BY e2.department, h.hours
) t JOIN employee e JOIN hours h ON e.id=h.id ON e.department = t.department AND t.total = h.hours
ORDER BY t.total DESC;
但这显示了疯狂的结果(我认为我的代码是疯狂的lol)
请帮忙!!
谢谢 如果出现平局,这将显示一个部门超过一行。也许是你想要的
SELECT EachEmp.name, EachEmp.department, MAXES.maxTotal AS total
FROM (SELECT e.name, -- sum up each employees totals
e.department,
SUM(h.hours) AS total
FROM employee e
JOIN hours h ON e.id = h.id
GROUP BY e.name, e.department) EachEmp
JOIN
(SELECT department, max(total) maxTotal -- get the maximum emp total for this dept
FROM ( SELECT e.department, SUM(h.hours) AS total
FROM employee e
JOIN hours h ON e.id = h.id
GROUP BY e.name, e.department) AS TOTAL -- note we are grouping by e.name
GROUP BY department) AS MAXES
ON EachEmp.department = MAXES.department
AND EachEmp.total = MAXES.maxTotal
ORDER BY MAXES.maxTotal DESC;
在Postgres中,最简单(通常也是最快)的方法是使用distinct on
:
SELECT DISTINCT ON (e.name) e.name, e.department, SUM(h.hours) AS total
FROM employee e JOIN
hours h
ON e.id = h.id
GROUP BY e.name, e.department
ORDER BY e.name, total DESC;
请用您实际使用的数据库标记您的问题。博士后?或MySQL?其Postgresql Sorry代码运行,但显示所有人员,而不是每个部门的最佳人员..您使用的是哪个数据库?它比旧数据库更好;)但是排序不正确,我的意思是,你应该努力解决它。我将查询修改为包含按总描述排序的
查询。对不起,非常感谢,我在回答之前尝试了一些“排序依据”。你是最棒的;)谢谢你,评论对理解每一行都很重要。