sql - select count of rows minus sum of another field -


i have 3 tables named agency, works , purchases. , there foreign key agency in purchases , works. every agency works , works saved in works table , give 1 point per each works do. example agency 200 works us, has 200 points.
each agency can buy our product points. in purchases table there field named price, if agency buy product insert purchases table. need sql query give me number of works of each agency minus sum of purchases!

like:

select count(works.wid)-sum(purchases.price) agency.aid='1' 

for example:
agency this:

 aid='1' name='firstagency'   

do works like:

wid='1' aid='1' description='clean floor'   wid='2' aid='1' description='clean window'  wid='3' aid='1' description='clean floor'   wid='4' aid='1' description='clean window'  wid='5' aid='1' description='clean floor'   wid='6' aid='1' description='clean window'  

so firstagency has 6 points because there 6 rows aid='1' in works table
, firstagency bought product products price 2. in purchases table:

pid='1' aid='1' price='2'   

so agency has 6-2=4 points now. need query this, compute remainder of agency points.

so problem have n works , m purchases , don't want join tables, because confronted n * m records.

you can this:

select   (select count(*) works w w.id_agency = a.id_agency) count_works,   (select sum(p.price) purchases p p.id_agency = a.id_agency) sum_purchases agency a.id_agency = 1; 

this possible joins, need math obfuscate statement. i'll show completeness' sake.

select   count(distinct w.id_work) count_works,   coalesce(sum(p.price),0) / greatest(count(distinct w.id_work),1) sum_purchases agency left join works w on w.id_agency = a.id_agency left join purchases p on p.id_agency = a.id_agency a.id_agency = 1; 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -