Group Results & Count Values In While Loop

时间:2015-11-12 12:01:02

标签: php mysql

I have a simple query that lists the employees name, the hours/minutes they have worked and the cost for those hours. Here is the query, it joins 3 tables:

$usersResult = mysqli_query($con,"SELECT a.UF_TIME_ID, a.UF_USER, a.UF_COST,
b.ID, b.NAME, b.LAST_NAME, c.ID, c.MINUTES, c.TASK_ID FROM time_cost a INNER
JOIN b_user b ON a.UF_USER = b.ID INNER JOIN b_tasks_elapsed_time c ON 
a.UF_TIME_ID = c.ID GROUP BY a.UF_USER");
while($row = mysqli_fetch_array($usersResult)

The minutes field is simply will read 120 for the number of minutes. I then have a function that splits this into hours and minutes. From this in the loop I get a table that looks like:

NAME          | Time Spent    | Cost
Bob           | 2h 30m        | 50
Bob           | 2h 15m        | 40
Dave          | 3h 30m        | 120
Bob           | 1h 15m        | 20
Dave          | 4h 30m        | 180

Now I want to group them, I have tried to GROUP BY a.UF_USER but it doesn't add the time or costs up correctly which I can understand. I have then tried:

SUM(c.MINUTES) AS TOTAL

And used that with and without the GROUP but that also doesn't add the values up correctly. I have also tried:

$totalTime += $row['MINUTES']; 

But again with grouping it doesn't display. Here is the code after the while loop I have:

   {
   $userFirstName = $row['NAME'];
   $userLastName = $row['LAST_NAME'];
   $userCost = $row['UF_COST'];
   $userMinutes = $row['MINUTES'];


   $userTime = $userMinutes;
   $userTime = convertFromMinutes($userTime);


   $totaluserHours = $userTime['hours'];
   $totaluserMinutes = $userTime['minutes'];

   print "<tr><td>$userFirstName $userLastName</td><td>$totaluserHours H $totaluserMinutes M</td><td>$userCost</td></tr>"; 
   }

I have a function that counts the minutes and splits into hours and minutes. So I need the end outcome to basically read:

NAME          | Time Spent    | Cost
Bob           | 6h 00m        | 110
Dave          | 8h 00m        | 300

Your help would greatly be appreciated. I'm sure it is simple and I'm missing the point here.

1 个答案:

答案 0 :(得分:1)

为了获得添加你需要一笔钱

试试这种方式

$usersResult = mysqli_query($con,"SELECT a.UF_TIME_ID, a.UF_USER, sum(a.UF_COST),
b.ID, b.NAME, b.LAST_NAME, c.ID, sum(c.MINUTES), c.TASK_ID FROM time_cost a  INNER
JOIN b_user b ON a.UF_USER = b.ID INNER JOIN b_tasks_elapsed_time c ON 
 a.UF_TIME_ID = c.ID GROUP BY a.UF_USER");