我在数据库中有以下表格,我需要计算收入(所有订单的售价总和),成本(所有销售产品的所有成本之和)和利润(收入减去成本)< / p>
sales_order的
id
grand_total (sum of sell_price of its items)
order_status (pending/complete)
delivery_date (date)
sales_order_item
id
sales_order_id
product_id (unique)
quantity (ordered quantity)
sell_price (sell price for single item)
PURCHASE_ORDER
id
status (pending / approved)
purchase_order_items
id
purchase_order_id
product_id
cost (cost of each item)
答案 0 :(得分:0)
加入sales_order_item
表格,明确了purchase_order_items
表格中的费用和产品,假设cost
在purchase_orders
之间不同时间。如果成本发生了变化,那么这可能会有点难看。
SELECT sum(sell_price*quantity) as revenue, sum(cost*quantity) as cost, sum(sell_price)-sum(cost*quantity) as profit
FROM sales_order_item
INNER JOIN (SELECT distinct cost, product_id FROM purchase_order_items) as product
ON sales_order_item.product_id = product.product_id