Home Forums SQL Server 2008 T-SQL (SS2K8) Join of two tables with sums of two different fields grouped by CustomerID RE: Join of two tables with sums of two different fields grouped by CustomerID

  • 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;

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001