我有一张这样的表:
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 |
我想查询一下:显示每个部门达到最大总小时数的人(从最大值到最小值排序)
| id | Name | Department | totalhours |
| 03 | Mark | Network | 27 |
| 02 | Sam | Quality | 26 |
我目前的代码不起作用,只显示每个人的总小时数:
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;
但这显示了疯狂的结果(我认为我的代码很疯狂)
请帮助!! 谢谢!
答案 0 :(得分:0)
view
答案 1 :(得分:0)
如果存在平局,这将为部门显示超过1行。可能你想要的是什么。
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;
答案 2 :(得分:0)
在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;