0

D B

Date        Price  qty
2012-10-21  $11 150
2012-10-22  $12 90
2012-10-22  $12 10
2012-10-23  $13 250

代码

$result = mysqli_query($con, "SELECT * FROM table ORDER BY 'date'");

    while ($row = mysqli_fetch_array($result)) {
        $orders[] = array(
            'Date' => $row['date'],
            'price' => $row['price'],
            'Quantity' => $row['qty']
        );
    }

我不需要获取重复的日期,对于那些重复的日期需要获取平均值price和总和,Qty如下例所示:

例子

Date        Price  qty
2012-10-21  $11 150
2012-10-22  $12 100
2012-10-23  $13 250

我尝试使用Array-map,但我失败了,非常感谢帮助

4

3 回答 3

2

GROUP BY我建议通过使用此查询和相应的聚合函数将问题移至数据库:

SELECT `date`, AVG( `price` ), SUM( `qty`)
FROM `table`
GROUP BY `date`
ORDER BY `date`

一般来说,让 MySQL 做这样的工作比首先将数据传输到您的应用程序并在那里重新排列更可取。

于 2013-11-03T07:21:32.720 回答
0

改变你的查询

SELECT Date, AVG(Price), SUM(Qty) FROM table
GROUP BY Date

或更改 php 以检查数组中的日期并计算平均值和总和

于 2013-11-03T07:22:37.163 回答
0

你可以试试这个,

   $result = mysqli_query($con, "SELECT date, AVG(Price) as price, SUM(qty) FROM table GROUP BY date ORDER BY date");

   while ($row = mysqli_fetch_array($result)) {
    $orders[] = array(
        'Date' => $row['date'],
        'price' => $row['price'],
        'Quantity' => $row['qty']
     );
   }
于 2013-11-03T07:24:43.773 回答