Ryan Gadsdon
Ryan Gadsdon

Reputation: 2378

Comparing SUM of values with different tables in SQL Server

I have two tables holding similar values, and I need to compare the two and find the differences between them:

SQL FIDDLE - http://sqlfiddle.com/#!6/7412e/9

Now you can see there is a difference between between the 2 tables for the figures in Jun-17.

AS you can see (as a total for everyone) table 1 has £75 for June but table 2 has £125 for june.

The result I'm looking for is when amounts are summed together and compared between tables on a monthly basis, if there is a difference in amount between the two tables I want it listed under 'Unknown'.

| MonthYear | Person | Amount | Month total
+-----------+--------+--------+--------------
|    Jun-17 |    Sam |     25 | 75(Table1)
|    Sep-17 |    Ben |     50 | 50(Table2)
|    Jun-17 |    Tom |     50 | 75(Table1)
|    Jun-17 |    Sam |     25 | 125(Table2)
|    Sep-17 |    Ben |     50 | 50(Table2)
|    Jun-17 |    Tom |     50 | 125(Table2)
|    Jun-17 |        |     50 | 125(Table2)

Now when there is a difference between the amount total over a month I want the difference to be classed as unknown

e.g

| MonthYear | Person | Amount | Month total
+-----------+--------+--------+--------------
|    Jun-17 |    Sam |     25 | 75(Table1)
|    Sep-17 |    Ben |     50 | 50(Table2)
|    Jun-17 |    Tom |     50 | 75(Table1)
|    Jun-17 |    Sam |     25 | 125(Table2)
|    Sep-17 |    Ben |     50 | 50(Table2)
|    Jun-17 |    Tom |     50 | 125(Table2)
|    Jun-17 | Unknown|     50 | 125(Table2)

I understand that you could create a case when the person is null to display unknown but i need it to be specifically calculated on the difference between the 2 tables on a monthly calculation.

Does this make sense to anyone, its really hard to explain.

Upvotes: 0

Views: 52

Answers (1)

simon at rcl
simon at rcl

Reputation: 7344

Generally, in any FROM clause a table name can be replaced with another SELECT as long as you give it a corelation name (t1 and t2 in this one):

SELECT t1.MonthYear, t1.AmountT1, t2.AmountT2, t1.amountT1 - isnull(t2.amountT2, 0) as Unknown'
from
  ( SELECT
    MonthYear, 
    SUM(Amount) AS [AmountT1]
    FROM
    Invoice  
    GROUP BY MonthYear) t1
left outer join
   ( SELECT 
     MonthYear, 
     SUM(Amount) AS [AmountT2]
     FROM
     Invoice2
     GROUP BY MonthYear) t2 on t2.MonthYear = t1.MonthYear

Upvotes: 3

Related Questions