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

时间:2019-03-21 11:27:24

标签: sql ms-access ms-access-2016

我正在尝试从“ 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

感谢您的帮助! 预先感谢

2 个答案:

答案 0 :(得分: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记录的那些客户显示零。

答案 1 :(得分:0)

您可以使用相关子查询:

<a
class="nav-link{f:if(condition: item.hasSubPages, then: ' dropdown-toggle')}"
href="{f:if(condition: item.hasSubPages, then:'#', else: '{item.link}')}"
{f:if(condition: item.hasSubPages, then:' data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"', else: '')}
pageUid="{item.uid}"
title="{item.title}">
{item.title}
</a>