mysql查询从下表中获取收入,成本和利润:

时间:2017-05-30 15:46:08

标签: mysql

我在数据库中有以下表格,我需要计算收入(所有订单的售价总和),成本(所有销售产品的所有成本之和)和利润(收入减去成本)< / 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)
    

1 个答案:

答案 0 :(得分:0)

加入sales_order_item表格,明确了purchase_order_items表格中的费用和产品,假设costpurchase_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