我们说我有这些表格:
tblPerson
id | name |
1 | A |
2 | B |
3 | C |
tblB
id | personId | loan |
1 | 1 | 100 |
2 | 1 | 50 |
3 | 2 | 25 |
tblC
id | personId | payment |
1 | 1 | 20 |
2 | 1 | 10 |
如何生成此输出:
Output
id | name | loan | payment | balance |
1 | A | 100 | 0 | 100 |
1 | A | 0 | 20 | 80 |
1 | A | 50 | 0 | 130 |
1 | A | 0 | 10 | 120 |
2 | B | 25 | 0 | 25 |
我需要先输出贷款,然后再贷款,等等。
答案 0 :(得分:1)
这种查询(http://sqlfiddle.com/#!2/759df4/3/0)将生成一组交错的贷款和付款。
SELECT id,name,loan,payment
FROM (
SELECT p.id id,
p.name name,
0 type,
b.id detail_id,
b.loan loan,
0 payment
FROM person p
JOIN b ON p.id = b.personId
UNION ALL
SELECT p.id id,
p.name name,
1 type,
c.id detail_id,
0 loan,
c.payment payment
FROM person p
JOIN c ON p.id = c.personId
) q
ORDER BY id, detail_id, type
然后,我想你可以使用变量来生成运行总计。但Linoff博士是正确的(见他的评论),你所展示的数据集并没有足够的信息可靠地交换贷款和付款记录。我已经使用ID字段来执行此操作。如果您在表格中的其他地方有ORDER BY
,则最后posting_date
确实应该提及detail_id
或其他一些信息,而不是{{1}}
答案 1 :(得分:0)
试试这个:
select *, (sum(tb.loan) / sum(tc.payment)) as balance
from tblPerson tp
join tblB tb on tp.id = tb.personId
join tblC tc on tp.id = tc.personId
这就是我的想法。