MS Access,从两个表中获取总值
MS Access, getting total values from two tables
我正在尝试从表 "sales" 和 "payment" 中获取总值,其中两个表中的 customer_id 与从表单的组合框中选择的客户相匹配。
Table 1:销售额
customer_id item item_value
1 Fan 0
3 AC 0
1 Iron
Table 2:付款
customer_id amount
1 0
2 0
1
4 0
我不确定如何编写查询以获得以下结果:
查询结果
customer_id total_purchase_amount total_paid_amount
1 250 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;
您可以加入两个求和表,例如:
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
记录的客户显示零。
我正在尝试从表 "sales" 和 "payment" 中获取总值,其中两个表中的 customer_id 与从表单的组合框中选择的客户相匹配。
Table 1:销售额
customer_id item item_value
1 Fan 0
3 AC 0
1 Iron
Table 2:付款
customer_id amount
1 0
2 0
1
4 0
我不确定如何编写查询以获得以下结果:
查询结果
customer_id total_purchase_amount total_paid_amount
1 250 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;
您可以加入两个求和表,例如:
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
记录的客户显示零。