我的SQL Server中有两个表,两个表具有相同的列。我需要找出这些表之间的区别。
表(所有字段均为nvarchar格式):
在表格列之后,我需要进行SQL查询以识别这种情况:
table1.uf = table2.uf,
table1.municipio = table2.municipio,
table1.marca_modelo = table2.marca_modelo,
table1.ano_fabricacao = table2.ano_fabricacao
table1.qtd_veiculos != table2.qtd_veiculos
和
`Unique lines in table1`
我已经尝试过进行此查询(下面),但是不起作用。
Select *
from Table1 J left join
Table2 M on J.uf = M.uf
and J.municipio = M.municipio
and J.marca_modelo = M.marca_modelo
and J.ano_fabricacao = M.ano_fabricacao
and J.qtd_veiculos != M.qtd_veiculos
您能帮我解决这个问题吗?
我希望收到以下结果:
红色字段显示表之间的差异,最后一行显示表1中的差异,表1中没有相关性。
我很抱歉缺乏信息,这是我在论坛中的第一个话题。但感谢您的帮助!
答案 0 :(得分:0)
这是我用来比较两个表的脚本。也许您可以通过将结果放入临时表中进行进一步分析来自己修改。 您可以更改“ *”以仅列出要比较的列。
-- Thisc script compares any two tables.
-- Enter the two tables names to compare in the first two lines.
DECLARE @table1 NVARCHAR(80)= 'my_first_table_to_compare'
DECLARE @table2 NVARCHAR(80)= 'my_second_table_to_compare'
DECLARE @sql NVARCHAR (2000)
SET @sql = '
SELECT ''' + @table1 + ''' AS table_name,* FROM
(
SELECT * FROM ' + @table1 + '
EXCEPT
SELECT * FROM ' + @table2 + '
) x
UNION
SELECT ''' + @table2 + ''' AS table_name,* FROM
(
SELECT * FROM ' + @table2 + '
EXCEPT
SELECT * FROM ' + @table1 + '
) y
'
EXEC sp_executesql @stmt = @sql
答案 1 :(得分:0)
我不完全理解您的问题,所以这是一个[疯狂的]猜测。您想找到:
qtd_veiculos
上它们不同。如果这是问题,查询应该是:
select j.*, m.*
from table1 j
outer join table2 m on j.uf = m.uf
and j.municipio = m.municipio
and j.marca_modelo = m.marca_modelo
and j.ano_fabricacao = m.ano_fabricacao
where j.qtd_veiculos <> m.qtd_veiculos