我有兩個表這樣比較有例外
Tableyesterday SQL Server的兩個表:
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的結果:
insert into Tableofchanges
select
Column1, Column2, Column3
from
[dbo].[tabletoday]
except
select
Column1, Column2, Column3
from
[dbo].[Tableyesterday]
where
tabletoday.Column4 = Tableyesterday.Column4
OR
INSERT INTO [dbo].[Tableofchanges] (Column1, Column2, Column3, Column4)
SELECT
Column1, Column2, Column3, Column4
FROM
[dbo].[Tableyesterday]
WHERE
(NOT EXISTS (SELECT Column1, Column2, Column3, Column4
FROM [dbo].[Tabletoday]
WHERE ([dbo].[Tableyesterday].Column1 = Column1)
AND ([dbo].[Tabletoday].Column1 = Column1)
AND ([dbo].[Tableyesterday].Column2 = Column2)
AND ([dbo].[Tabletoday].Column2 = Column2)
AND ([dbo].[Tableyesterday].Column3 = Column3)
AND ([dbo].[Tabletoday].Column3 = Column3)))
非常感謝你對解決我的查詢
您如何識別行 UNION 記錄? Column1是主鍵,因此您可以比較具有相同Column1的行並在Column2和Column3中查找更改? –
是的,但主鍵有一天可以是新的,第二天可以走。MARK + NICOL – terka
爲什麼你不能做SELECT Column1,Column2,Column3,Column4 FROM TableToday EXCEPT選擇Column1,Column2,Column3,Column4 FROM TableYesterday。這應該從今天拿起與昨天不同的所有行,或者我錯過了什麼? –