表A包含应从表B中删除的多条记录。但是,表B中可能有多条记录与表A中的单条记录匹配。我只想删除表B中每条记录的第一条匹配记录在表A中。如果表A中有50条记录,则应从表B中删除最多50条记录。我正在使用下面的SQL语句,该语句将删除表B中比表A中列出的更多记录火柴。由于数据的限制,我无法在声明中进一步限制匹配条件。
DELETE FROM [#DraftInvoiceRecords] FROM [#DraftInvoiceRecords]
INNER JOIN [#ReversedRecords]
ON [#DraftInvoiceRecords].employee = [#ReversedRecords].employee
and [#DraftInvoiceRecords].amount = [#ReversedRecords].amount
and [#DraftInvoiceRecords].units = [#ReversedRecords].units
答案 0 :(得分:0)
您需要一些方法来区分要删除的行以保留。我在下面使用了someOtherColumn
来实现这个目标:
create table #DraftInvoiceRecords (
employee int not null,
amount int not null,
units int not null,
someOtherColumn int not null
)
create table #ReversedRecords (
employee int not null,
amount int not null,
units int not null
)
insert into #DraftInvoiceRecords (employee,amount,units,someOtherColumn)
select 1,1,1,1 union all
select 1,1,1,2
insert into #ReversedRecords (employee,amount,units)
select 1,1,1
delete from dir
from
#DraftInvoiceRecords dir
inner join
#ReversedRecords rr
on
dir.employee = rr.employee and
dir.amount = rr.amount and
dir.units = rr.units
left join
#DraftInvoiceRecords dir_anti
on
dir.employee = dir_anti.employee and
dir.amount = dir_anti.amount and
dir.units = dir_anti.units and
dir.someOtherColumn > dir_anti.someOtherColumn --It's this condition here that allows us to distinguish the rows
where
dir_anti.employee is null
select * from #DraftInvoiceRecords
drop table #DraftInvoiceRecords
drop table #ReversedRecords