MS SQL将两个表与异常进行比较

时间:2017-09-01 13:46:21

标签: sql sql-server database sql-server-2008

我有两张这样的表

Tableyesterday

Column1 Column2  Column3     Column4 
John     5584    samsung     2017-08-31 23:43:06.867
Bob      4512    apple       2017-08-31 23:43:06.867
Hana     1881    nokia       2017-08-31 23:43:06.867
Hanz     4866    alcatel     2017-08-31 23:43:06.867
Nicol    48633   android     2017-08-31 23:43:06.867  ---gone

Tabletoday

Column1 Column2     Column3     Column4 
John     5584       samsung     2017-09-01 23:43:06.867 ---same entry
Bob      4542446    apple       2017-09-01 23:43:06.867 ---change in column2
Hana     1881       halophone   2017-09-01 23:43:06.867 ---change in column3 
Hanz     4866       alcatel     2017-09-01 23:43:06.867 ---same entry
Mark     486654     alcatel     2017-09-01 23:43:06.867 ---new entry

我需要选择今天的更改并插入tableofchanges。只需要选择这两行:

Tableofchanges

Bob      4542446    apple       2017-09-01 23:43:06.867
Hana     1881       halophone   2017-09-01 23:43:06.867

我创建了这个查询,但是我不能包含Column4。但是,如果我选择不使用Column4,我将不会在结果中看到Column4:

select Column1, Column2,Column3 from [dbo].[tabletoday]
except
select Column1, Column2,Column3 from [dbo].[Tableyesterday]

1 个答案:

答案 0 :(得分:0)

尝试此操作以从第4列中提取值。

SELECT
    E.Column1
    ,E.Column2
    ,E.Column3
    ,T.Column4
FROM
(   
select Column1, Column2,Column3 from [dbo].[tabletoday]
except
select Column1, Column2,Column3 from [dbo].[Tableyesterday]
) AS E
    INNER JOIN [dbo].[tabletoday] AS T
        ON
        E.Column1 = T.Column1