简体   繁体   English

如何获取一组mysql记录的平均值?

[英]How to get the average value of a set of mysql records?

I have a table with a set of fields.我有一个包含一组字段的表。 Each of these fields contains a number between one and 10.这些字段中的每一个都包含一个介于 1 和 10 之间的数字。

|item_id|field1|field2|field3|field4|
|1      | 2    |5     |2     |9     |
|3      | 9    |3     |5     |10    |
|4      | 9    |9     |9     |10    |

What I would like to do is get the average of these fields.我想做的是获得这些领域的平均值。 However, I need the number to be between 10 and 100.但是,我需要这个数字在 10 到 100 之间。

First what you wanna do is multiply the rating by 10;首先,您要做的是将评分乘以 10;

foreach ($results as $result) {
    $rating = 0;
    $rating = $rating + $result['field1']         + $result['field2'] + $result['field3'] + $result['field4'];

    // Multiply rating by 10
    $rating = $rating*10;

    // Devide rating by 4
    $rating = $rating/4;

    // Output average
    echo $result['item_id']." : ".$rating."<br />";
}

Or you could do it even simpler while doing your query:或者您可以在进行查询时更简单地做到这一点:

SELECT
(field1 + field2 + field3 + field4)*10/4 AS average
FROM table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM