一行的总和

时间:2012-09-11 14:22:31

标签: php mysql

我有这个查询给了我一个用户的交易,输出是一个包含信息的表。这行名为basket_value,其中包含一些数字,我需要得到这些数字的总和。你能帮我吗?

$query3 = 'SELECT users.first_name,users.last_name,users.phone,
           retailer.date, SUM(retailer.basket_value), 
           retailer.time,retailer.location,retailer.type_of_payment
           FROM users ,retailer 
           WHERE users.user_id="'.$id_user.'"
           AND users.user_id=retailer.user_id GROUP BY users.user_id';

$result3 = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result3)) {
    echo "Total ". $row['user_id']. " = $". $row['SUM(basket_value)'];
    echo "<br />";
}

4 个答案:

答案 0 :(得分:0)

您在查询中遗漏了GROUP BY。您最有可能想要添加GROUP BY users.user_id

答案 1 :(得分:0)

您可以省略选择列表中的所有其他列,并且只在集合上运行sum()聚合以避免GROUP BY子句。

$query3 = 'SELECT SUM(retailer.basket_value) as total_sum
FROM users ,retailer WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id';

答案 2 :(得分:0)

我想你的查询也存在一些问题,并假设你有id来检索用户,我会这样做

$query3 = 'SELECT users.user_id,users.first_name,users.last_name,
                  users.phone, retailer.date, 
                  SUM(retailer.basket_value) as total_sum,
                  retailer.time,retailer.location,retailer.type_of_payment
           FROM users ,retailer WHERE users.user_id="'.$id_user.'"
           AND users.user_id=retailer.user_id
           GROUP BY users.user_id,users.first_name,users.last_name,
                    users.phone, retailer.date,retailer.time,retailer.location,
                    retailer.type_of_payment '

$result = $mysqli->query($query3);

现在,如果您想要每个用户的总和:

while ($row = $result->fetch_row()) {
        echo "Player: ".$row['user_id']." total: ".$row['total_sum'];
    }

如果你想要全球总和,你必须:

  • 以这种方式修改您的查询:

    SELECT SUM(retailer.basket_value) as total_sum                 
    FROM retailer
    
  • 汇总到while循环:$total += $row['total_sum'];

答案 3 :(得分:0)

尝试此查询:

SELECT u.first_name, u.last_name, u.phone, SUM(r.basket_value) as total_sum
FROM users u
JOIN retailers r
  ON u.user_id = r.user_id
WHERE u.user_id="'.$id_user.'"
GROUP BY u.user_id