繁体   English   中英

MySQL查询-从具有相同ID的多行添加数据并将其放置在表中

[英]Mysql query - add data from multiple rows with the same id and place them in a table

我有这个MySQL表,我想添加具有相同clientID的totalUnits和订单总数。

OrderID   clientID     name       pay       totalUnits     total
1            1           A        Paid          2           200
2            2           B        Paid          1           150
3            1           A        Paid          1           100

这应该是输出

clientID     name     totalOrders     totalUnits     totalSales
1             A            2             3               300
2             B            1             1               150

当我执行以下代码时,我仍然得到3行而不是2行。我该怎么办? 谢谢您的帮助!

$orders = $wpdb->get_results("SELECT * FROM wp_orderrecords WHERE pay = 'Paid' AND paymentDate BETWEEN '".$from."' AND '".$to."'");

foreach($orders as $order){
   $orderID = $order->orderID;
   $clientID = $order->clientID;
   $total = $order->total;

   $results = $wpdb->get_results("SELECT * FROM wp_clients WHERE clientID = '".$clientID."%'");     
           foreach($results as $order){
                  $clientsName = $order->clientsName;
           } 

           $sales = $wpdb->get_results("SELECT * FROM wp_orderrecords WHERE pay = 'Paid' AND clientID = '".$clientID."'");
           foreach($sales as $sale){
                  $total = $sale->total;
                  $totalUnits = $sale->totalUnits;

                  $totalSales = $totalSales + $total;
                  $totalProducts = $totalProducts + $totalUnits;
           }  

           $orderItem = array(
                    'clientID' => $clientID,
                    'clientsName' => $cName,
                    'totalOrders' => $totalOrders,
                    'totalProducts' => $totalProducts,
                    'totalSales' => $totalSales
                 );
           $records[] = $orderItem;
}
echo json_encode($records);
SELECT 
    clientId,name,
    count(totalUnits) as totalOrders,
    sum(totalUnits) as totalUnits, 
    sum(total) as totalSales 
FROM wp_orderrecords 
GROUP BY clientId,name

暂无
暂无

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

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