SQL Server递归CTE多对多“最佳匹配”

时间:2017-09-17 23:44:44

标签: sql-server tsql recursion common-table-expression

我有多对多的关系。我想确定最佳匹配。

@firstParty.StartDate@thirdParty.MatchRangeStart之间的匹配= @thirdParty.MatchRangeEnd

最佳匹配= @thirdParty中最早的记录,与@firstParty中的早期记录不是“最佳匹配”。

出于性能原因,我无法使用循环。所以,我认为需要一个递归的CTE。

这是我想要的输出:

FirstPartyId StartDate  ThirdPartyId ThirdPartyStartDate
------------ ---------- ------------ -------------------
1            2016-01-01 1            2016-01-10
2            2016-01-02 2            2016-01-11
3            2016-01-03 3            2016-01-12

脚本:

declare @firstParty table
(
    FirstPartyId integer identity,
    StartDate date,
    ThirdPartyId integer
);

insert into @firstParty (StartDate)
values
('01/01/2016'), ('01/02/2016'), ('01/03/2016'), ('01/04/2017'), ('01/05/2017');

/*
dates in @firstParty and @thirdParty are not guaranteed to be unique 
in all scenarios
*/

declare @thirdParty table
(
    ThirdPartyId integer identity,
    StartDate date,
    MatchRangeStart date,
    MatchRangeEnd date
);

insert into @thirdParty (StartDate)
values
('01/10/2016'), ('01/11/2016'), ('01/12/2016');


update @thirdParty set MatchRangeStart = dateadd(d, -31, StartDate), MatchRangeEnd = dateadd(d, 31, StartDate);

declare @matches table 
(
    Id integer identity,
    FirstPartyId integer,
    FirstPartyStartDate date,
    ThirdPartyId integer,
    ThirdPartyStartDate date
);

insert into @matches (FirstPartyId, FirstPartyStartDate, ThirdPartyId, ThirdPartyStartDate)
select
    fp.FirstPartyId,
    fp.StartDate,
    tp.ThirdPartyId,
    tp.StartDate
from
    @thirdParty tp
    join @firstParty fp on
        fp.StartDate between tp.MatchRangeStart and tp.MatchRangeEnd
        ;




select
    fp.FirstPartyId,
    fp.StartDate,
    tpm.ThirdPartyId,
    tpm.ThirdPartyStartDate 
from
    @firstParty fp
    cross apply
    (
        select top 1
            m.*
        from
            @matches m
        where
            fp.FirstPartyId = m.FirstPartyId
        order by
            m.ThirdPartyStartDate
    ) tpm;

0 个答案:

没有答案