[英]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 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. 现在您可以看到,Jun-17中的两个表之间存在差异。
AS you can see (as a total for everyone) table 1 has £75 for June but table 2 has £125 for june. 正如您所看到的(所有人的总和),表1的6月价格为75英镑,表2的6月价格为125英镑。
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 现在,当一个月的总金额之间存在差异时,我希望将差异归类为未知
eg 例如
| 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. 这对任何人有意义吗,这真的很难解释。
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): 通常,在任何FROM子句中,只要为表名指定一个核心名称(此名称中的t1和t2),即可将其替换为另一个SELECT:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.