-1
$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所有订单产品的)总和跟随 order by group by。它看起来像如何编写相同的 sql 来选择feeship_totalsum(cost)

4

1 回答 1

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退货列表和表格中其产品数量的总和,order_products这些产品中的每一个都乘以products表格中相应的价格。此结果集与来自每个结果集JOIN的列上的订单。orderid然后GROUP BY,如果您GROUP BY订购年份,您可以选择任何您想要的列。

于 2012-06-21T08:11:09.587 回答