簡體   English   中英

如何獲取一組mysql記錄的平均值?

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

我有一個包含一組字段的表。 這些字段中的每一個都包含一個介於 1 和 10 之間的數字。

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

我想做的是獲得這些領域的平均值。 但是,我需要這個數字在 10 到 100 之間。

首先,您要做的是將評分乘以 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 />";
}

或者您可以在進行查詢時更簡單地做到這一點:

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