2015-11-12 178 views
0

我有這樣的一個表:SQL要避免重複行

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   | 

我目前的代碼不工作,只顯示總小時數o f每個人:

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

請與您實際使用的數據庫標記您的問題。 Postgres的?還是MySQL? –

+0

它的Postgresql對不起 – frau1337

回答

0
select id, name, department, total 
from 
(
SELECT e.id, e.name, e.department, t.total, 
rank() over(partition by e.department order by t.total desc) as rnk 
FROM (
SELECT id, SUM(hours) AS total 
FROM hours 
GROUP BY id 
) t JOIN employee e ON e.id = t.id 
) t 
where rnk = 1 
order by total desc 
+0

代碼運行,而是顯示所有人,而不是從每個部門最好.. – frau1337

+0

你使用哪個數據庫? –

+0

它比舊的更好;)但沒有正確排序,我沒有排序我的意思。 – frau1337

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; 
+0

謝謝你,這些評論對於理解每一行非常重要。 – frau1337

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;