扣除相同产品和帐单编号的销售退货后,通过SQL查询显示销售额

时间:2018-01-29 09:43:54

标签: php mysql sql database

我的数据库中有一张表(销售),用于记录销售和销售退货。 enter image description here

销售退货与status='sr'一起记录 我想在扣除销售退货后显示每件产品的最终数量。 产品B0801180323NA的示例包含quantity:2的销售退货以及quantity:2的销售,因此现在必须显示的最终数量为0

4 个答案:

答案 0 :(得分:1)

您可以使用具有相同表格的联接以及按产品划分的总和组别

select a.products, sum(a.quantity) -  ifnull(sum(b.quantity),0)
from sales 
left join sales on a.products = b.products and b.status = 'sr'
where a.status = 'sale' 
group by a.products

答案 1 :(得分:1)

我会使用子查询

select products,
       (
          select sum(quantity) from sales s2 where s2.products = s1.products and status = 'sale'
       ) -
       (
          select sum(quantity) from sales s2 where s2.products = s1.products and status = 'sr'
       )
from (select distinct products from sales) s1

答案 2 :(得分:1)

SELECT products, SUM(IF(status='sale',quantity,0)) - SUM(IF(status='sr',quantity,0)) AS quantity 
FROM sales
GROUP BY bill_id, products;

根据'状态计算数量'专栏,减去销售额'来自'sr'的。

答案 3 :(得分:1)

select sum(a.quantity) - coalesce(sum(b.quantity), 0) as total_quantity, a.bill_id, a.product_id 
from sales a
left join sales b on a.bill_id = b.bill_id and a.product_id = b.product_id
and b.status = 'sr'
where a.status = 'sales'
group by a.bill_id, b.product_id