$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_total
和sum(cost)
?
答案 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
任意列。