我有三个表,名为agency
、works
和purchases
。agency
在purchases
和works
中有一个外键。每个代理机构都为我们工作,这些作品保存在works
表中,并且每做一件作品就会给出一分。例如,一个机构为我们做了200个工作,所以它有200个积分。
每一家代理商都可以按他们的积分购买我们的产品。在purchases
表中有一个名为price
的字段,如果代理购买产品,它将插入到purchases
表中。我需要一个SQL查询,给我每个机构的作品数量减去其购买的总和!
比如:
select count(works.WID)-SUM(purchases.price) where agency.aid='1'
例如:
像这样的机构:
AID='1' name='FirstAgency'
做一些工作,比如:
WID='1' AID='1' Description='Clean the floor'
WID='2' AID='1' Description='Clean the window'
WID='3' AID='1' Description='Clean the floor'
WID='4' AID='1' Description='Clean the window'
WID='5' AID='1' Description='Clean the floor'
WID='6' AID='1' Description='Clean the window'
所以FirstAgency有6个点,因为在Works
表中有6行AID='1‘
FirstAgency购买了产品价格为2的产品,如Purchases
表中所示:
PID='1' AID='1' Price='2'
所以这个机构现在有6-2=4分了。我需要一个查询来完成这个任务,计算代理点的剩余部分。
发布于 2014-06-02 12:03:47
所以问题是,你有n个工作和m购买,你不想加入表,因为你会突然面对n*m记录。
你可以这样做:
select
(select count(*) from works w where w.id_agency = a.id_agency) as count_works,
(select sum(p.price) from purchases p where p.id_agency = a.id_agency) as sum_purchases
from agency a
where a.id_agency = 1;
这在联接中也是可能的,但是您需要一些数学来混淆语句。为了完整起见,我会展示给你看。
select
count(distinct w.id_work) as count_works,
coalesce(sum(p.price),0) / greatest(count(distinct w.id_work),1) as sum_purchases
from agency a
left join works w on w.id_agency = a.id_agency
left join purchases p on p.id_agency = a.id_agency
where a.id_agency = 1;
https://stackoverflow.com/questions/23993546
复制相似问题