0

我有三张桌子:

1. user    => user_id[Pk], user_name
2. payment => payment_id[PK], user_id[FK], amount
3. receive => receive_id[PK], user_id[FK], amount

现在我想获取如下记录:

用户名、付款金额、应收金额

提前致谢..

我读过这个,但它对我不起作用。

假设,在用户表中

user_id 用户名
1 ABC
2 XYZ

在付款表中

payment_id user_id 金额
1 1 1000
2 1 200
3 2 150

在接收表中:
receive_id user_id amount
1 2 100
2 1 200

现在我想要像这样的记录

用户名 付款金额 应收金额
ABC 1000 200
ABC 200
XYZ 150 100

4

5 回答 5

2

您可能希望按 user_id 汇总金额。

SELECT
    user.user_id,
    SUM(payment.amount) AS payment_amount,
    SUM(receive.amount) AS receive_amount
FROM (receive INNER JOIN [user] ON receive.user_id = user.user_id)
              INNER JOIN payment ON user.user_id = payment.user_id
GROUP BY user.user_id;
于 2012-09-15T19:18:22.853 回答
1

使用内置的查询设计器。将三个表拖入其中,链接键(将字段拖放到彼此上),双击要添加到底部字段列表的字段,然后运行查询。如果需要,选择聚合表达式。

于 2012-09-15T21:14:01.350 回答
0
select t1.user_name, t2.amount payementamount, t3.amount receiveableamount from 
User t1,
payment t2,
receive t3
where
t1.user_id=t2.user_id and
t1.user_id=t3.user_id

你可以试试这个......

于 2012-09-15T19:21:02.697 回答
0

您可能需要将此调整为 MSAccess 语法,但其想法是LEFT JOIN与用户一起执行付款和接收表,因为这是父表,而其他两个表可能有也可能没有此用户的记录。

SELECT 
    u.user_name, 
    ISNULL(p.amount, 0) as paymentamount,
    ISNULL(r.amount, 0) as receivableamount
FROM 
    user u
    LEFT JOIN payment p
    ON u.user_id = p.user_id
    LEFT JOIN receive r
    ON u.user_id = r.user_id
于 2012-09-15T19:15:31.560 回答
0
select 
    user.user_name, payment.amount, receive.amount 
from user 
    join payment on user.user_id == payment.user_id 
    join receive on user.user_id = receive.user_id; 
于 2012-09-15T19:17:13.277 回答