简体   繁体   中英

Sum and compare columns from different tables and databases

I have two tables I'd like to compare. They are in separate databases and servers as well. I've added a linked server and can query this from within Server 1.

Table1 on Server1 provides breakdowns of submitted data. For example ref#123 may appear 3 times with values of 100, 150, and 200 (total 450 ). I want to compare Table2 on Server2 that also has ref#123 and the totals, and return the correct record if the total is different to 450 .

Hope this makes sense! Thanks

select *
from
(select col1, SUM(col2)
from table1
group by col1) t1 INNER JOIN
(select col1, col2
from table2) t2 ON t1.col1 = t2.col1 where t1.col2 <> t2.col2

table 1 is table where ref#123 can appear multiple times. col2 contains values 100,150,200 etc

SELECT *
FROM
(
    SELECT
      ref,
      SUM(values) values
    FROM Server1.YourDb1.YourSchema.TableBreakdowns
) t1
FULL JOIN Server2.YourDb1.YourSchema.TableTotals t2
  ON t1.ref = t2.ref
WHERE t1.values <> t2.values OR t1.ref is null OR t2.ref is null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM