2011-03-25 62 views
2

我想這將是簡單的,但我掙扎(可能是週五的大腦)分組查詢(透視風格?)

我有一個表:

 
Staff  department  job_date  job    Hours 
--------------------------------------------------------------- 
Chris  Software  2011-03-02  Writing Code 3 
Chris  Software  2011-03-04  Holiday   7 
Bob  QA    2011-03-02  Testing   4 
Frank  Design   2011-03-11  Meeting   1 

現在,我需要一個查詢這將「組」,結果一天的基礎上,什麼作業領域,即..所以我得到的每名員工花了幾個小時之做的工作,也爲假期:

結果集:

 
Staff   Worked Hours  Holiday Hours Department 
--------------------------------------------------------------- 
Chris   3     7    Software 
Bob    4     0    QA 
Frank   1     0    Design 
--------------------------------------------------------------- 
Total   8     7 

感謝您的幫助!

克里斯

+0

你說' 「組」 的結果通過day'但似乎只有員工分組。你能澄清嗎? – 2011-03-25 11:34:23

+1

對不起,忽略該日期欄......這僅僅是爲了獲得特定月份的條目......您可以忽略此練習。 – Chris 2011-03-25 11:37:10

回答

1
SELECT department, staff, 
     SUM(IF(job = 'Holiday', 0, hours)) AS work_hours, 
     SUM(IF(job = 'Holiday', hours, 0)) AS holiday_hours 
FROM mytable 
GROUP BY 
     department, staff WITH ROLLUP 
+0

謝謝。煩人。我也知道......星期五腦子! – Chris 2011-03-25 12:18:13

0
select staff, 
     sum(case when job='holiday' then 0 else hours end) `Worked Hours`, 
     sum(case when job='holiday' then hours else 0 end) `Holiday Hours`, 
     department 
from tbl 
group by staff, department