2017-03-29 35 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