合并ALMOST重复记录IN sql

时间:2012-01-20 15:34:21

标签: sql-server merge

祝贺所有人......

我有两张桌子,结构相同......

表logDetail

Date              Time         CardID        Status  
2012-01-20        00:00:00     A1            ABSENT
2012-01-20        00:00:00     B1            ABSENT
2012-01-20        00:00:00     C3            ABSENT
2012-01-20        00:00:00     D1            ABSENT

表preStatus

Date            Time        CardID        Status
2012-01-20     07:00:10     A1            COMING
2012-01-20     07:10:00     C3            COMING
2012-01-20     08:00:00     B1            LATE
2012-01-20     17:00:00     B1            BACK
2012-01-20     17:10:10     A1            BACK
2012-01-20     17:13:00     C3            BACK

合并后

Date
2012-01-20     07:00:10     A1            COMING
2012-01-20     07:10:00     C3            COMING
2012-01-20     08:00:00     B1            LATE
2012-01-20     00:00:00     D1            ABSENT
2012-01-20     17:00:00     B1            BACK
2012-01-20     17:10:10     A1            BACK
2012-01-20     17:13:00     C3            BACK

我如何合并这两个表,因为在表b中有重复的记录,当我这样做 合并......

merge into logDetail as Target 
using preStatus as Source
on Target.L_Date=Source.L_Date
and Target.L_Time='00:00:00'
and Target.L_CardID=Source.L_CardID 
when matched then

update set Target.L_Status=Source.L_Status,
Target.L_Time=Source.L_Time
when not matched then
insert (L_Date,L_Time,L_CardID,L_Status) 
                           values(Source.L_Date,Source.L_Time,Source.L_CardID,Source.L_Status);

它说MERGE语句试图多次更新或删除同一行

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您似乎不想合并表格,因为CardID不是主键。

看起来你想保留Status =" COMING"即使有新的条目,其中stats =" BACK"。

我建议你分两步完成,首先插入preStatus数据,然后删除" ABSENT"存在的行" COMING"和" BACK"行。

/* Insert new data */
insert logDetail
select * from preStatus

/* Delete Absent rows where there is a COMING or BACK row for the same item on the same day */
Delete logDetail
from logDetail ld1
where 
    /* Absent rows only */
    ld1.time = '00:00:00'
and ld1.Status = 'ABSENT'
/*  And there must be a COMING or BACK row for the same card on the same day */
and exists (
   select 1 from logDetail ld2
   where ld2.Date = ld1.Date
   and ld2.CardID = ld1.CardID
   and ld2.Time > '00:00:00'
   and ld2.Status <> 'ABSENT'
)

要删除相同日期,CardID和相同状态的行,但有较晚时间的行:

Delete logDetail
from logDetail ld1
where 
ld1.status in ('COMING', 'BACK')
/*  COMING or BACK row only */ 
      /* for the same card on the same day, with a later time*/
and exists (
   select 1 from logDetail ld2
   where ld2.Date = ld1.Date      
   and ld2.CardID = ld1.CardID
   and ld2.Status = ld1.Status
   and ld2.Time > ld1.Time
)

答案 1 :(得分:0)

匹配时不要做任何事情,这应该解决吗?