连接两个表时删除重复记录



我必须连接2个表并检查是否有任何重复的记录。如果有的话,我需要从dbo表中删除重复的记录

阶段表

market cost ra file_id 
CA     32   2   200
CA     44   5   200
TX     22   2   200

dbo表

market cost ra  file_id
CA     72   9    100
CA     44   5    100
TX     22   2    100

当我连接stage和dbo表时,我想删除重复的记录

我想看到的输出是:

dbo表

market cost ra  file_id
CA     72   9    100

I tried query:

select s.market, s.cost,s.ra , s.[file_id] ,count(*)
from stage table s
join dbo table d on s.market=d.market and  s.cost=d.cost, s.ra=d.ra
group by  s.market, s.cost,s.ra , s.[file_id]    
having count(*) > 1;

一旦我删除了重复的记录,我将把分级数据摄取到dbo。

有谁能帮我一下delete语句吗?

一个解决方案是使用EXISTS

DELETE 
FROM dbo_table
WHERE  EXISTS (
select 1
from stage_table s
WHERE s.market = dbo_table.market AND  dbo_table.cost = s.cost AND  s.ra=dbo_table.ra)

;
GO
<>之前行影响
SELECT * FROM dbo_table
GO
market | cost | ra | file_id:----- |——:| -:| ------:CA | 72 | 9 | 100

db<此处小提琴>

我试着猜测一下需求,因为在我看来你不是很清楚。你试着描述你实现解决方案的方法。
最好先说明你想要达到的目标。

你也没有明确定义你所说的重复记录是什么意思。我猜当列market,costra具有相等的值时(无论其他列),那么您认为它是重复的。

我猜是:

  • 要将staging的数据插入dbo
  • 问题是有些行是重复的,您希望在插入它们之前覆盖或删除它们

您可以在插入之前删除它们。

delete from dbo d where exists (select 'X' from staging s where s.market = d.market and s.cost = d.cost and s.ra = d.ra)

然后插入

insert into dbo select market, cost, ra, file_id from staging
我相信你能理解SQL语句,所以我不会在这里解释它们。请随意评论。

最新更新