0

表Aには、表Bから削除する必要のある複数のレコードが含まれています。ただし、表Aの単一のレコードと一致する表Bの複数のレコードが存在する可能性があります。表Aの各レコードについて、表Bの最初に一致するレコードのみを削除します。 。表Aに50レコードある場合は、最大50レコードを表Bから削除する必要があります。以下のSQLステートメントを使用して、複数の一致のために表Aにリストされているよりも多くのレコードを表Bから削除しています。データの制限により、ステートメントの一致基準をさらに制限することはできません。

DELETE FROM [#DraftInvoiceRecords] FROM [#DraftInvoiceRecords]
INNER JOIN [#ReversedRecords]
ON [#DraftInvoiceRecords].employee = [#ReversedRecords].employee 
  and [#DraftInvoiceRecords].amount = [#ReversedRecords].amount
  and [#DraftInvoiceRecords].units = [#ReversedRecords].units
4

1 に答える 1

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
于 2012-05-30T06:48:19.837 に答える