SQL计算单元格值之间的差异

时间:2021-11-13 20:27:17

Hi i was wondering if anyone knows how i can calculate the difference between two tables in tsql. I dont mean finding which cells are different - i mean calulcating the numerical difference. eg - Table A has column1, column 2 and only one 1 row. A1 = 40, B1 = 30. Table B has column1, column 2 and only one 1 row. A1 = 25, B1 = 10. So how could i get (A1 = 15, B1 = 20) using TSQL?

嗨我想知道是否有人知道如何计算tsql中两个表之间的差异。我不是说找出哪些细胞是不同的 - 我的意思是计算数字差异。例如 - 表A有第1列,第2列,只有1行。 A1 = 40,B1 = 30.表B有第1列,第2列,只有1行。 A1 = 25,B1 = 10.那么我怎么能用TSQL得到(A1 = 15,B1 = 20)?

3 个解决方案

#1


2  

Given that you have no way to join the tables, you'll need a Cartesian product of the two. Luckily since each table only has one record that's not a problem.

鉴于您无法加入表格,您需要两者的笛卡尔积。幸运的是,因为每个表只有一个记录不是问题。

You do it like this:

你这样做:

SELECT 
  TableA.A1 - TableB.A1 AS A1,
  TableA.B1 - TableB.B1 AS B1
FROM TableA, TableB

If you had more than one record in each table, this query would return a result for every pair of records in both tables. So if TableA had n records and TableB has m, the result will have n*m records.

如果每个表中有多个记录,则此查询将返回两个表中每对记录的结果。因此,如果TableA有n条记录且TableB有m,则结果将有n * m条记录。

#2


1  

SELECT  a.column1 - b.column1 , a.column2 - b.column2
FROM    a
CROSS JOIN
        b

#3


1  

Free from my mind =)

从我的脑海中解脱出来=)

Select 
(CONVERT(int, T1.A1) - Convert(int, T2.A1)) as A1,
(CONVERT(int, T1.B1) - Convert(int, T2.B)) as B1 
From Table1 T1
inner join Table2 T2 on  T1.Key = T2.Key

#1


2  

Given that you have no way to join the tables, you'll need a Cartesian product of the two. Luckily since each table only has one record that's not a problem.

鉴于您无法加入表格,您需要两者的笛卡尔积。幸运的是,因为每个表只有一个记录不是问题。

You do it like this:

你这样做:

SELECT 
  TableA.A1 - TableB.A1 AS A1,
  TableA.B1 - TableB.B1 AS B1
FROM TableA, TableB

If you had more than one record in each table, this query would return a result for every pair of records in both tables. So if TableA had n records and TableB has m, the result will have n*m records.

如果每个表中有多个记录,则此查询将返回两个表中每对记录的结果。因此,如果TableA有n条记录且TableB有m,则结果将有n * m条记录。

#2


1  

SELECT  a.column1 - b.column1 , a.column2 - b.column2
FROM    a
CROSS JOIN
        b

#3


1  

Free from my mind =)

从我的脑海中解脱出来=)

Select 
(CONVERT(int, T1.A1) - Convert(int, T2.A1)) as A1,
(CONVERT(int, T1.B1) - Convert(int, T2.B)) as B1 
From Table1 T1
inner join Table2 T2 on  T1.Key = T2.Key