# Query to calculate total

How can I create one SQL that will give me a 'TOTAL' from:

The result of this:

SELECT   (  SUM  (UnitCost  * Qty)- (SUM ( PmtRecd))   ) AS BALANCE
FROM dbo.BillingLines WHERE CaseId = 20816  Group by  CaseId

Minus the result of this:

SELECT SUM (Amount) as total
FROM dbo.PaymntSchedule WHERE   Caseid = 20816
LVL 1
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ProgrammerCommented:
``````SELECT BALANCE-COALESCE((SELECT SUM(Amount) FROM dbo.PaymntSchedule WHERE Caseid = z.CaseId),0) as RESULT
from
(
SELECT CaseId, SUM(UnitCost * Qty)-SUM(PmtRecd) AS BALANCE
FROM dbo.BillingLines WHERE CaseId = 20816
Group by CaseId
) z
``````
0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Business Systems Analyst , ex-Senior Application EngineerCommented:
or something like:

``````Select bal1.BALANCE - bal2.total Total from
(
SELECT   (  SUM  (UnitCost  * Qty)- (SUM ( PmtRecd))   ) AS BALANCE
FROM dbo.BillingLines WHERE CaseId = 20816  Group by  CaseId
) bal1,
(
SELECT SUM (Amount) as total
FROM dbo.PaymntSchedule WHERE   Caseid = 20816
) bal2
``````
0
Commented:
Possibly a join?
``````SELECT   (  SUM  (UnitCost  * Qty)- (SUM ( PmtRecd))   ) - SUM (Amount) AS Total
FROM dbo.BillingLines B join dbo.PaymntSchedule P on B.caseid=P.caseid
WHERE b.CaseId = 20816
``````
0
ProgrammerCommented:
If there are no any rows selected from PaymntSchedule, then answer from slightwv (䄆 Netminder) and from Ryan Chong will not work.
0
Commented:
If there are no payments then make mine a LEFT JOIN?

``````SELECT   (  SUM  (UnitCost  * Qty)- (SUM ( PmtRecd))   ) - SUM (Amount) AS Total
FROM dbo.BillingLines B left join dbo.PaymntSchedule P on B.caseid=P.caseid
WHERE b.CaseId = 20816
``````

I'm not seeing why Ryan's will not work?  The second query should return a 0 if there are no payments.
0
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.