2016-02-24 19 views
2

目前使用以下查询:MySQL的 - 需要检索muliple顾问的数据 - 选择SUM似乎防止

select distinct(shift_report.advisor), users.team, shift_report.date 
from shift_report join users on shift_report.advisor=users.username 
where `date` >=20160224 
and users.team=1 

这给了我的数据为每个顾问。我想计算花费每个总时间不过,当我添加下面的查询只返回一个顾问的数据,但时间等似乎是球队总数:

SUM(shift_report.time) as total_time, round(SUM(shift_report.time)/450 * 100,2) 
as percentage 

当我运行上面包括查询工作的个人的SUM。

+1

您的查询缺少'group by'子句,因此sum()会将输出折叠为单个记录。您需要提供您想通过哪些字段显示总和。我的猜测是shift_report.advisor,users.team,shift_report.date – Shadow

回答

1

当使用聚合函数,你必须通过条款,以获得(在这种情况下,顾问),每个分区的结果,所有这列指定一组

select shift_report.advisor, users.team, shift_report.date, 
     SUM(shift_report.time) as total_time, round(SUM(shift_report.time)/450 * 100,2) 
from shift_report join users on shift_report.advisor=users.username 
where `date` >=20160224 
and users.team=1 
GROUP BY shift_report.advisor,users.team,shift_report.date 

我以为你要组(顾问,团队,日期)如果不是,请将它们从分组中删除

+0

你可以删除distinct并将它放在GROUP BY中,因为它不是一个函数 – Mihai

+0

谢谢 - 完美的工作,正是我需要的。 – djd

+0

没问题:) @GrahamDrummond – sagi