应用GROUP BY ID时,SUM添加不正确

时间:2014-01-30 09:10:54

标签: php mysql sql

我需要帮助找出我的代码中有关逻辑错误的错误,我无法弄清楚为什么会发生错误,下面是我的代码:

$consultants = mysqli_query($con,"SELECT a.ID, a.USER_ID, a.TASK_ID, SUM(a.MON_BILL+a.TUE_BILL+a.WED_BILL+a.THU_BILL+a.FRI_BILL) AS conhours, a.DELETE_WEEK, b.ID, b.NAME, b.LAST_NAME, c.REF, SUM(c.EXPENSE_COST) AS consultantexpenses, c.DELETE_WEEK FROM b_report_week a INNER JOIN b_user b ON a.USER_ID = b.ID INNER JOIN b_report_expense2 c ON a.ID = c.REF WHERE a.DELETE_WEEK = 0 AND c.DELETE_WEEK = 0 GROUP BY a.USER_ID");
while($row = mysqli_fetch_array($consultants))
{
$conFN = $row['NAME'];
$conLN = $row['LAST_NAME'];
$totalConHours = $row['conhours'];
$totalConExpenses = $row['consultantexpenses'];

print "<tr><td>".$conFN." ".$conLN."</td><td>".$totalConHours."</td><td>".$totalConExpenses."</td>";

}

未正确添加的部分是这部分:

SUM(a.MON_BILL+a.TUE_BILL+a.WED_BILL+a.THU_BILL+a.FRI_BILL) AS conhours

基本上有五列,每列有值和多行。行中还包含USER_ID,因此我想在USER_ID相同的这些列中添加所有值。我的语句末尾有GROUP BY设置为a.USER_ID,这是正确的。

奇怪的是,有些数字是正确的,但有些数字并非如此,真正令人困惑。我从数据库中获得了电子表格以添加正确的数字,这就是我知道一些是正确的,有些是错误的。

任何帮助表示感谢。

实施例

USER_ID   |   MON_BILL  |  TUE BILL  |  WED_BILL  |  THU_BILL  |  FRI_BILL
24        |   8         |  8         |  8         |  8         |  8
24        |   8         |  8         |  8         |  8         |  8
24        |   8         |  8         |  8         |  8         |  8
20        |   8         |  8         |  8         |  8         |  8  
20        |   8         |  8         |  8         |  8         |  8    

所以USER_ID 24总小时数应该等于:120而USER_ID 20 = 80.它不会像那样添加它。

1 个答案:

答案 0 :(得分:0)

我认为您可能需要使用以下内容:

SUM(a.MON_BILL)+SUM(a.TUE_BILL)+SUM(a.WED_BILL)+SUM(a.THU_BILL)+SUM(a.FRI_BILL) AS conhours