MS Access,从两个表中获取总值

问题描述 投票:1回答:2

我试图从表“sales”和“payment”中获取总值,其中两个表中的customer_id与从表单中的组合框中选择的客户匹配。

表1:销售额

customer_id item    item_value
1           Fan     $200
3           AC      $500
1           Iron    $50

表2:付款

customer_id amount
1           $150
2           $300
1           $50
4           $100

我不知道如何编写查询以获得以下结果:

查询结果

customer_id total_purchase_amount   total_paid_amount
1           250                     $200

非常感谢您的帮助!提前致谢

sql ms-access ms-access-2016
2个回答
0
投票

您可以使用相关子查询:

select s.customer_id, sum(s.item_value) as total_purchase_amount,
       (select sum(p.amount) 
        from Payment p 
        where p.customer_id = s.customer_id
       ) as total_paid_amount
from Sales s
where s.customer_id = ? -- you can pass here customer_id
group by s.customer_id;

1
投票

你可以加入两个求和表,例如:

select a.customer_id, a.total_purchase_amount, b.total_paid_amount
from
    (
        select s.customer_id, sum(s.item_value) as total_purchase_amount
        from sales s
        group by s.customer_id
    ) a left join
    (
        select p.customer_id, sum(p.amount) as total_paid_amount
        from payment p
        group by p.customer_id
    ) b on a.customer_id = b.customer_id

要按从组合框中选择的客户进行筛选,可以包含where子句,例如:

where a.customer_id = Forms!YourForm!YourComboBox

您可能还希望使用Nz(b.total_paid_amount, 0)为没有Payment记录的客户显示零。

© www.soinside.com 2019 - 2024. All rights reserved.