I have 3 tables
Tbcodetable
codevalue | codename | desc1 | desc2
1 | SATO | NAG | Naga
2 | SATO | BAG | Baguio
3 | SATO | NCR | Head Office
Tbmember
employeeno | capcon_accountno | savings_accountno | sato
1 | 00101 | 00201 | NCR
2 | 00102 | 00202 | BAG
Tbdeposit
employeeno | account_no | accountbalance
1 | 00101 | 1000
1 | 00201 | 5000
2 | 00102 | 1000
2 | 00202 | 5000
What I want to query is sum of capital and savings per sato in one query
codename | codevalue | desc1 | desc2 | capcon | savings
SATO |3 |Head Office |NCR |1000 | 5000
SATO |2 |Baguio |BAG |1000 | 5000
SATO |1 |Naga |NAG |0 | 0
The best query I could do is
SELECT codename,codevalue,desc1,desc2,sum(b.accountbalance) as capcon
FROM TBCODETABLE c
left join TBMEMBER a on c.desc2 = a.SatoCode
join tbdeposit b on a.employeeno = b.employeeno
where a.SLAStatus = 'A' and c.codename ='sato'
group by codename, codevalue, desc1, desc2
which gives me this result
codename | codevalue | desc1 | desc2 | capcon
SATO |1 |Head Office |NCR |1000
SATO |2 |Baguio |BAG |1000
This only gives me the sum of capital(Im lost on how include both savings and capital on result.) and it doesnt include the naga region
I could join tbmember and tbdeposit by employeeno but then I dont know how to separate sum of capital and savings in the result set
Edit
I edited the query and now Im able to query both thanks to syed but I still cant get the NAG sato code.
Query:
SELECT codename,codevalue,desc1,desc2, coalesce(sum(b.accountbalance),0) as savings, coalesce(sum(bb.accountbalance),0) as capcon FROM TBCODETABLE c left join TBMEMBER a on c.desc2 = a.SatoCode join tbdeposit b on a.SAVINGS_AccountNo = b.AccountNo
inner join tbdeposit bb on a.CAPCON_Accountno = bb.AccountNo where a.SLAStatus = 'A'
group by codename, codevalue, desc1, desc2
I am able to get the expected result thank you guys chris's left join advice solved my NAG SATO problem though Syed's reply helped me big time.
I dont how to upvote a reply so i'll just upvote chris(first time here.)
My final query is :
SELECT codename,codevalue,desc1,desc2, coalesce(sum(b.accountbalance),0) as savings, coalesce(sum(bb.accountbalance),0) as capcon FROM TBCODETABLE c left join TBMEMBER a on c.desc2 = a.SatoCode left join tbdeposit b on a.SAVINGS_AccountNo = b.AccountNo
left join tbdeposit bb on a.CAPCON_Accountno = bb.AccountNo where a.SLAStatus = 'A' or codename = 'sato'
group by codename, codevalue, desc1, desc2