汇总相同日期的所有值

时间:2017-10-25 07:46:03

标签: php mysql database

我想通过使用产品ID来总结同一日期的所有amount条目。

数据库图片:

DATABASE

我想用php和mysql这样的方式显示结果。

Required

1 个答案:

答案 0 :(得分:1)

这是一个可能的解决方案。数据库表已命名为tborderdetail

/* I get data using json object (for convenience): */
    $arr = [];
    $s = "SELECT product_name, SUM(amount) AS amount, DATE_FORMAT(order_date,'%d %b %Y') AS order_date FROM tborderdetail GROUP BY product_name, DATE_FORMAT(order_date,'%d %b %Y') ORDER BY order_date DESC";
    $q1 = mysqli_query($con,$s); 
    while($row = mysqli_fetch_assoc($q1)){$arr[] = $row;} 
    $str = json_encode($arr);
    $data = json_decode($str);

    /* Populate three arrays that will be used to create the required table */
    $arr_dates = [];
    $arr_products = [];
    $arr_date_product_amount = [];

    foreach($data as $v){ 
    if(!in_array($v->order_date, $arr_dates)){ $arr_dates[] = $v->order_date; }
    if(!in_array($v->product_name, $arr_products)){ $arr_products[] = $v->product_name;}
    $dpv = str_replace(' ','',$v->product_name.$v->order_date);
    $arr_date_product_amount[$dpv] = $v->amount;}

    /* Start outputting the table and the top row */
    echo '<table><tr><td>Products</td>'; 
    foreach($arr_dates as $dt){ echo '<td>Sale on '.$dt.'</td>'; } 
    echo '</tr>';

    /* Output the other rows of the table: */
    foreach($arr_products as $pt){
    echo '<tr><td>'.$pt; 
    foreach($arr_dates as $dt){
    $dpv = str_replace(' ','',$pt.$dt);
    /* Ensure no errors due to missing values */
    echo '<td>'; if(array_key_exists($dpv,$arr_date_product_amount)){echo $arr_date_product_amount[$dpv];}
    echo '</td>';}
    echo '</tr>';}
    echo '</table>';