2017-03-29 36 views
0

我有一個小時,這看起來像一個表:我怎樣才能金額/組通過此表的結果

enter image description here

我要總結的僅此一週,組結果由hours_spent結果created_by人。我有這樣的查詢返回正確的數據,只顯示結果在這一週:

enter image description here

SELECT staff_id, first_name, last_name, date_entered, `hours_spent` as total_hours FROM hours LEFT JOIN staff ON hours.created_by = staff.staff_id where yearweek(`date_entered`) = yearweek(curdate()); 

但是當我通過staff_id添加SUM(hours_spent)爲total_hours和組像下面的例子中,我得到0結果。

enter image description here

SELECT staff_id, date_entered, first_name, last_name, SUM(`hours_spent`) as total_hours FROM hours LEFT JOIN staff ON hours.created_by = staff.staff_id group by staff_id having yearweek(`date_entered`) = yearweek(curdate()); 

我猜想它不工作,因爲我的發言的有一部分不返回日期的各行,以便它打破。

我覺得我這樣做很難。我應該試着對第一個查詢的結果進行第二次總結查詢,而不是將它們合併爲一個(我希望保持清潔)。或者我應該使用子查詢來過濾不是本週的日期,然後將總計分組,如果有的話我怎麼能做到這一點?

+1

嘗試按hours.created_by進行分組,並註釋掉您的語句。這應該確保你的連接是正確的,並看看有沒有過濾掉結果。 –

回答

0

我得到了我與期待:

SELECT staff.first_name,staff.last_name,SUM(hours_spent) 從數小時 LEFT JOIN工作人員hours.created_by = staff.staff_id WHERE年周(date_entered, 1)=(yearweek(curdate(),1)-1) GROUP BY created_by