查找每个用户的平均数

时间:2017-11-30 12:36:28

标签: php mysqli

首先,我对编码很新。在来到这里寻求建议之前,我尽力做好尽职调查。

我正在尝试编写一个函数,该函数将在数据库中查询用户数并获取每个用户的平均值。

function getUserAverage($userID) {
    //loop through user totals & calculate average for each user
    $sql = "select p.userID, p.user, p.number ";
    $sql .= "from " . DB_PREFIX . "numbers p ";
    $sql .= "inner join " . DB_PREFIX . "users u on p.userID = u.userID ";
    $sql .= "where u.userID = " . $user->userID . " ";
    $sql .= "order by u.lastname, u.firstname";
    $query = $mysqli->query($sql);
    while ($row = $query->fetch_assoc()) {
        //player average of numbers
        $tba = ROUND(AVG(`number`),2);

    }
    $query->free;
    return $tba;
    }

我希望得到的结果是:

user1 = 14.5 user2 = 35.8 user3 - 7.4

我已编写代码来获取所有人的平均数字,但需要由个人用户获取。

//Average Numbers

$sql_avgNum = "SELECT ROUND(AVG(`number`),2) AS `Average` \n"
. "FROM `" . DB_PREFIX . "numbers` \n";
$data = $mysqli->query($sql_avgNum);
$result_avgNum = mysqli_fetch_array($data);
echo ' <tr class="altrow"><td> Average Number: </td><td> ' . 
$result_avgNum[0] . ' </td></tr>';

//End Average Numbers 

2 个答案:

答案 0 :(得分:0)

对于单个数据的计数平均值,您必须使用group by执行此操作。 group by的进一步参考是here

答案 1 :(得分:0)

我不太确定,但我认为这就是您正在寻找的内容:

function getUserAverage($userID) {
    // loop through user totals & calculate average for each user
    $sql = "SELECT p.userID, u.user, AVG(p.number) AS 'avarage' ";
    $sql .= "FROM " . DB_PREFIX . "numbers p ";
    $sql .= "INNER JOIN " . DB_PREFIX . "users u ON(p.userID = u.userID) ";
    $sql .= "WHERE p.userID = " . $user->userID . " ";
    $sql .= "GROUP BY p.userID ";
    $sql .= "ORDER BY u.lastname, u.firstname";
    $query = $mysqli->query($sql);

    while ($row = $query->fetch_assoc()) {
        //player average of numbers
        $tba = $row['avarage'];

    }

    $query->free;
    return $tba;
}