briancampbellmcad (6/13/2016)
I'm not following the placing of the literal amounts into the SQL. Shouldn't I just be using field names
He's putting the example data into CTEs... It's the same as if he showed you the solution like this:
-- Sample Data
DECLARE @charges TABLE ([ChargeAmount] money,[PeopleID] int);
DECLARE @payments TABLE ([Amount] money,[PeopleID] int);
INSERT @charges
SELECT 100.00, 54215 UNION ALL
SELECT 125.00, 53252 UNION ALL
SELECT 110.00, 63225 UNION ALL
SELECT 10.00, 54215 UNION ALL
SELECT 10.00, 53252 UNION ALL
SELECT 15.00, 63225;
INSERT @payments
SELECT 75.00, 54215 UNION ALL
SELECT 25.00, 53252 UNION ALL
SELECT 50.00, 63225 UNION ALL
SELECT 10.00, 54215 UNION ALL
SELECT 25.00, 53252 UNION ALL
SELECT 25.00, 63225;
-- Solution
WITH
NetCharges
AS
(
SELECT SUM([ChargeAmount]) As TotalCharges ,[PeopleID] FROM @Charges GROUP BY [PeopleID]
),
NetPayments
AS
(
SELECT SUM([Amount]) As TotalPayments ,[PeopleID] FROM @Payments GROUP BY [PeopleID]
)
SELECT c.peopleID,
TotalCharges,
TotalPayments,
TotalCharges - TotalPayments as [Balance]
FROM NetCharges c
inner join NetPayments p
on c.peopleid = p.peopleid;
-- Itzik Ben-Gan 2001