如何(订购的所有商品的产品_价格的总和)按照“分组”的顺序?

时间:2012-06-21 07:27:57

标签: mysql sql sum

$query = "SELECT sum(o.feeship) feeship_total,
(SELECT SUM(p.products_price) FROM products p 
 left join orders_products op on op.products_id = p.products_id  
 WHERE op.orders_id = o.orders_id) AS cost 
FROM orders o ";
$query .= " GROUP BY year(o.date_purchased), month(o.date_purchased)";
if ($sel_month<>0) 
    $query .= ", dayofmonth(o.date_purchased)";
$query .=  " ORDER BY o.date_purchased";

使用上述SQL,只有第一个订单的所有产品select sum products_price。如何(sum products_price所有订单产品)的总和遵循group by的顺序。看起来如何编写相同的SQL来选择feeship_totalsum(cost)

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT YEAR(o.date_purchased) AS PurchaseYear, SUM(sub.ptotal) AS feeship_total
FROM orders o
INNER JOIN
( 
   SELECT op.order_id, SUM(p.products_price * op.quantity) as ptotal
   FROM products p
   LEFT JOIN order_products op ON p.product_id = op.product_id
   GROUP BY op.order_id
) sub ON o.order_id = sub.order_id
GROUP BY YEAR(o.date_purchased), MONTH(o.date_purchased)
ORDER BY 1;

INNER JOIN返回订单列表及其产品总和&#39;来自order_products表的数量,每个产品乘以products表中的相应价格。 JOIN此结果集与每个结果集中orderid列的订单一起设置。然后,如果您GROUP BY订购年份,您可以GROUP BY任意列。