我有三张桌子。我插入的第三个更改是在表1和2之间创建的
我的问题是我无法修复删除语句,我尝试从column1'Dog'中删除。表3应仅包含一天中值的更改。
Table1 ---Yesterday
Column1 Column2 Column3 Column4
Dog Blue 555 poo
Dog Brown 666 hoo
Dog Black 666 hoo
Mouse Red 888 nic
Cat Ping 444 pic
Table2 ---Today
Column1 Column2 Column3 Column4
Dog Colour 555 poo ---Change column2
Dog Brown 888 hoo ---Change column3
Dog Black 666 hoo --- No change
Mouse Red 888 nicoo ---Change column4
Cat Ping 444 pic --- No change
Table3 ---Changes between days
Column1 Column2 Column3 Column4
Dog Colour 555 poo ---Change column2
Dog Brown 888 hoo ---Change column3
Dog Black 666 hoo --- No change
Mouse Red 888 nicoo ---Change column4
Table3 ---Expect Output
Mouse Red 888 nicoo ---Change column4
Dog Colour 555 poo ---Change column2
Dog Brown 888 hoo ---Change column3
SELECT *
FROM [dbo].[Table3]
WHERE Column1 = 'Dog' and ( EXISTS
(SELECT *
FROM [dbo].[Table2]
WHERE ([Table2].Column1 = Column1) AND ([Table2].Column1 = Column1
and
[Table3].[Column1] <> [Table1].[Column1] or
[Table3].[Column2] <> [Table1].[Column2] or
[Table3].Column3 <> [Table1].Column3 or
[Table3].Column4 <> [Table1].Column4 or
)))
感谢您帮助我找到删除声明的解决方案!
答案 0 :(得分:0)
您可以通过正确加入 -
来实现这一目标create table #Table1 (Column1 varchar(10) ,Column2 varchar(10) ,Column3 int,Column4 varchar(10))
insert into #Table1
select 'Dog' ,'Blue', 555 ,'poo'
union all select 'Dog' ,'Brown', 666 ,'hoo'
union all select 'Dog' ,'Black', 666 ,'hoo'
union all select 'Mouse' ,'Red', 888 ,'nic'
union all select 'Cat' ,'Ping', 444 ,'pic'
create table #Table2 (Column1 varchar(10) ,Column2 varchar(10) ,Column3 int,Column4 varchar(10))
insert into #Table2
select 'Dog', 'Colour', 555 ,'poo'
union all select 'Dog', 'Brown', 888 ,'hoo'
union all select 'Dog', 'Black', 666 ,'hoo'
union all select 'Mouse', 'Red', 888 ,'nicoo'
union all select 'Cat', 'Ping', 444 ,'pic'
select t2.*
from #Table1 t1
right join #Table2 t2
on t1.Column1 = t2.Column1
and t1.Column2 = t2.Column2
and t1.Column3 = t2.Column3
and t1.Column4 = t2.Column4
where t1.Column1 is null
--OUTPUT
Column1 Column2 Column3 Column4
Dog Colour 555 poo
Dog Brown 888 hoo
Mouse Red 888 nicoo