| payments | | transactions | | transaction_items |
|:--------------:| |:------------:| |:-----------------:|
| id | | id | | id |
| date | | number | | transaction_id |
| amount | | date | | description |
| transaction_id | | val | | price |
| discount |
| quantity |
我正在尝试显示交易记录中的付款清单,并显示每次付款后的当前余额。以下是预期结果的示例
| number | DATE(p.date) | total | paid | balance |
| 1355 | 2016-10-31 | 899.00 | 450.00 | 449.00 |
| 1355 | 2016-12-06 | 899.00 | 449.00 | 0.00 |
| 1359 | 2016-09-28 | 4045.00 | 1515.00 | 2530 |
| 1359 | 2016-10-24 | 4045.00 | 35.00 | 2495.00 |
| 1361 | 2016-09-28 | 1548.00 | 1548.00 | 0.00 |
这是到目前为止的查询,但是where子句有错误
select
t.number,
DATE(p.date),
ti.total 'total',
SUM(p.amount) 'paid',
ti.total - paid.total 'balance'
from payments p
left join transactions t
on p.transaction_id = t.id
left join (
select inner_ti.transaction_id, sum((inner_ti.price - inner_ti.discount) * inner_ti.quantity) 'total'
from transaction_items inner_ti
group by inner_ti.transaction_id
) ti on t.id = ti.transaction_id
left join (
select inner_p.transaction_id, sum(inner_p.amount) 'total'
from payments inner_p
where inner_p.date <= p.date -- error unknown column p.date
group by inner_p.transaction_id
) paid on t.id = paid.transaction_id
group by t.number, DATE(p.date), ti.total, paid.total
order by DATE(p.date) ASC
请注意,我正在分组,p.date
因为我们关注的是一天之内的总付款额。
有人可以启发我为什么会出错吗?是否有任何变通方法可以达到预期的结果?