SQL:查询客户销售分类帐

时间:2014-09-29 10:34:43

标签: mysql sql

当特定用户支付现金时,请插入下表

payments:
description     | Amount    | Date      |   custid 
cash            | 2000      | 2014-9-24 | 5
cash            | 3000      | 2014-9-26 | 5

当特定用户购买产品时,请插入下表

orders
Product         | qty   | amount  |  date      | custid
front light     |  2    |  3000   | 2014-9-22  | 5
back light      |  2    |  2500   | 2014-9-22  | 5
  • 如果上表需要更改,也会引导我。?
  • 是付款表中任何需要余额列的。 ?
  • 请记住,如果借记卡中有任何错误,请告诉我,我是程序员而不是会计师。

我需要这样的结果或类似的东西(客户/客户账户详细信息的销售总账)。什么是SQL查询?

Product     | Debit  |  Credit      | Balance 
opening bal |        |              | 0
product     | 5500   |              | 5500
cash        |        | 2000         | 3500
cash        |        | 3000         | 500 

1 个答案:

答案 0 :(得分:1)

首先,你没有"打开bal"的数据,所以我忽略了这一点。完全不清楚它来自哪里。

获取前三列(包含日期)是将表连接在一起的问题。为此,union all是最佳方法:

select *
from ((select custid, 'product' as product, date, sum(amount) as amount, -1 as dir
       from orders
       group by custid, date, amount
      ) union all
      (select custid, description, date, 1 as dir
       from payments
      )
     ) op;

接下来是添加累积片段。在MySQL中,您可以使用变量:

select custid, product, date, amount,
       (@bal := if(@c = custid, @bal + amount * dir,
                   if(@c := custid, 0, 0)
                  )
       ) as bal
from ((select custid, 'product' as product, date, sum(amount) as amount, -1 as dir
       from orders
       group by custid, date, amount
      ) union all
      (select custid, description, date, amount, 1 as dir
       from payments
      )
     ) op cross join
     (select @c := -1, @bal := 0) vars
order by custid, date, dir desc