【发布时间】:2017-08-16 20:45:01
【问题描述】:
我有一张这样的表(交易)
ID | Name | Unit |Quantity_in|Quantity_out|transaction_date|
-----|-------| --------|-----------|------------|----------------|
100 | aaaa | packet | 100 | 0 | 02/07/2017 |
99 | cccc | packet | 70 | 0 | 20/06/2017 |
99 | cccc | packet | 0 | 20 | 22/07/2017 |
100 | aaaa | strip | 0 | 30 | 05/07/2017 |
102 | bbbb | packet | 50 | 0 | 29/06/2017 |
我想进行查询以获取两天之间的交易和当前余额,同时获取 WHERE 条件中日期之前的先前余额,因此我进行以下查询
select d.ID, d.Name, d.Unit, (select sum(tr.Quantity_in)- sum(tr.Quantity_out) from transactions tr where tr.transaction_date 作为 Prev_bal,sum(d.Quantity_in), sum(d.Quantity_out), Prev_bal +(sum(d.Quantity_in)- sum(d.Quantity_out)) 作为 current_balance from交易d 其中 d.transaction_date 介于 01/07/2017 和 30/07/2017 之间 按 d.ID、d.Name、d.Unit 分组
但是下面的查询结果没有包含ID 102,因为Where条件中的日期之间没有交易
ID | Name | Unit | Prev_bal | Quantity_in | Quantity_out |Current_balance|
----|------| ------ |----------|-------------|---------------|---------------|
100 |aaaa |packet | 0 | 100 | 30 | 70
----|----- |--------|----------|-------------|---------------|---------------|
99 |cccc |packet | 70 | 0 | 20 | 50 |
即使 WHERE 条件中的日期之间没有交易(如表中的 ID 102),任何人都可以帮助我进行查询以获取所有具有余额的 ID 的结果。 我需要获取当前余额 (Current_balance),其中两个日期之间的 transaction_date 和前一个余额 (Prev_bal) 的 ID 的余额为 transaction_date
标识 |姓名 |单位 |上一页 |数量_in | Quantity_out |Current_balance|
100 |aaaa |数据包 | 0 | 100 | 30 | 70
99 |cccc |数据包 | 70 | 0 | 20 | 50 |
102 |bbbb |数据包 | 50 | 0 | 0 | 50 |
【问题讨论】:
-
您需要提供更多详细信息。什么是表“d”?你需要什么输出?您在查询中使用了 SUM,但没有指定任何分组子句。
-
感谢注释我调整查询以添加总和和 d
-
对于输出,我需要获取当前余额 (Current_balance),其中 2 个日期之间的 transaction_date 以及具有余额的 ID 的上一个余额 (Prev_bal),其中 transaction_date
-
如果在您的日期范围之后有交易会发生什么?
-
没问题,我只需要日期范围内的报告