【问题标题】:display sales through sql query after subtracting sales return of same product and bill number减去相同产品的销售退货和账单号后通过sql查询显示销售额
【发布时间】:2018-01-29 09:43:53
【问题描述】:

我的数据库中有一个记录销售和销售退货的表(销售)。

销售退货记录在status='sr' 我想在扣除销售退货后显示每种产品的最终数量。 例如产品B0801180323NA 有销售退货quantity:2 和销售quantity:2 所以现在必须显示的最终数量是0

【问题讨论】:

  • 每件产品的销售和销售退货可以多吗?
  • 是的,但是会通过账单 ID 来区分
  • 在所有这些销售和销售退货之后,您想要每个产品的最终数量,对吧?
  • 是的,bill_idproduct 将只有一次销售和一次销售退货
  • 这里的大多数人想要格式化的文本,而不是图像。

标签: php mysql sql database


【解决方案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”列中减去“销售”列。

【讨论】:

  • 您可能需要根据需要交换“sale”和“sr”,目前从“sale”中减去“sr”
  • 其他人也给出了正确的解决方案,但您的解决方案非常简单。谢谢兄弟
【解决方案2】:

我会使用子查询

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

【讨论】:

  • Gettig 在select 的最后一行出现错误,即This type of clause was previously parsed
【解决方案3】:

您可以在按产品的总和组上使用具有相同表和差异的联接

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

【讨论】:

  • 无效? - 我更喜欢colsce
  • 这是innull还是isnull
【解决方案4】:
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 

【讨论】:

    猜你喜欢
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2021-01-20
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多