【问题标题】:SQL: Query for customer sales ledgerSQL:查询客户销售账本
【发布时间】:2018-02-17 18:18:12
【问题描述】:

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

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 

【问题讨论】:

  • 所以您对在结果中包含日期不感兴趣?
  • yes date's must be included and , 也用于 where 条件。我没有写在上表中以消除复杂性。
  • 我认为我们可以处理这种复杂程度。清晰度也很重要。

标签: mysql sql


【解决方案1】:

首先,您没有“open 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

【讨论】:

  • 另外,PK 应该是一个严肃的考虑。
  • #1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取正确的语法,以便在 'as dir ) 附近使用 union all ( select custid, desc' 在第 7 行
  • 这适用于 MySQL 视图吗?如果没有,您能否将其转换为可以创建为视图的形式?我只能在我的持久类中调用表或视图。谢谢!
  • @BorgyManotoy 。 . .如果您对创建视图有任何疑问,请将其作为问题提出,而不是在评论中提出。
  • 谢谢兄弟,稍后会发布问题。
猜你喜欢
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-29
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多