我在一个名为#MPR的表中有一组记录。我想要完成的是在该表中找到在另一个名为#Lookup的表中具有重叠日期的记录,并且具有匹配的ProviderID,Sub Type,CauseID和CircuitID。如果是,则返回#MPR表中的所有记录以及#Lookup表中相应的重叠记录,其中包含以下列LookupID,BegDate,EndDate和Amt。
-- Create Temporary Table
CREATE TABLE #MPR
(
MprID int IDENTITY(1,1),
ProviderID int,
RowNo int,
SubType varchar(50),
CauseID int,
CircuitID int,
BegDate date,
EndDate date,
Amt decimal(11,2),
Remarks varchar(max)
)
--Insert records
INSERT INTO #MPR VALUES(673,2,'Original',439,4852,'2016-12-01','2016-12-31',100,'Rec A')
INSERT INTO #MPR VALUES(673,15,'Original',439,4852,'2016-12-21','2016-12-31',200,'Rec B')
INSERT INTO #MPR VALUES(100,21,'Original',500,5000,'2016-12-01','2016-12-01',300,'Rec C')
INSERT INTO #MPR VALUES(673,24,'Original',439,4852,'2016-12-05','2017-01-31',400,'Rec D')
-- Create Temporary Table
CREATE TABLE #Lookup
(
LookupID int IDENTITY(1,1),
ProviderID int,
SubType varchar(50),
CauseID int,
CircuitID int,
BegDate date,
EndDate date,
Amt decimal(11,2),
)
--Insert records
INSERT INTO #Lookup Values(673,'Original',439,4852,'2016-10-01','2016-10-31',200.00)
INSERT INTO #Lookup Values(100,'Original',500,5000,'2016-10-01','2016-10-31',200.00)
INSERT INTO #Lookup Values(100,'Original',500,5000,'2016-10-01','2016-11-30',200.00)
INSERT INTO #Lookup Values(673,'Original',439,4852,'2016-11-01','2016-11-30',200.00)
INSERT INTO #Lookup Values(673,'Original',439,4852,'2016-12-01','2016-12-31',200.00)
INSERT INTO #Lookup Values(673,'Original',439,4852,'2017-01-01','2017-01-31',200.00)
INSERT INTO #Lookup Values(100,'Original',500,5000,'2016-12-01','2016-12-31',200.00)
INSERT INTO #Lookup Values(673,'Original',439,6565,'2017-01-01','2017-01-31',200.00)
--Drop table #mpr
--Drop table #Lookup
我的结果:
MprID ProviderID RowNo SubType CauseID CircuitID BegDate EndDate Amt LookupID BegDate EndDate Amt
----------- ----------- ----------- -------- ----------- ----------- ---------- ---------- --------- ----------- ---------- ---------- --------
1 673 2 Original 439 4852 2016-12-01 2016-12-31 100.00 5 2016-12-01 2016-12-31 200.00
2 673 15 Original 439 4852 2016-12-21 2016-12-31 200.00 5 2016-12-01 2016-12-31 200.00
3 100 21 Original 500 5000 2016-12-01 2016-12-01 300.00 7 2016-12-01 2016-12-31 200.00
4 673 24 Original 439 4852 2016-12-05 2017-01-31 400.00 5 2016-12-01 2016-12-31 200.00
4 673 24 Original 439 4852 2016-12-05 2017-01-31 400.00 6 2017-01-01 2017-01-31 200.00
答案 0 :(得分:2)
如果我已正确阅读您的规格,这将做您想要的。请注意,到目前为止,它仅使用两个条件而不是另一个条件中的四个条件。
SELECT
m.*,
l.LookupId,
l.BegDate,
l.EndDate,
l.Amt
FROM
#MPR m
INNER JOIN #Lookup l
ON m.ProviderID = l.ProviderID
AND m.SubType = l.SubType
AND m.CauseID = l.CauseID
AND m.CircuitID = l.CircuitID
WHERE
m.BegDate < l.EndDate
AND l.BegDate < m.EndDate
;
答案 1 :(得分:1)
我认为这会做你想做的事情
select *
from #mpr M
inner join #Lookup L
on M.ProviderID = L.ProviderID
AND M.SubType = L.SubType
AND M.CauseID = L.CauseID
AND M.CircuitID = L.CircuitID
AND (M.BegDate BETWEEN L.BegDate AND L.EndDate OR L.BegDate BETWEEN M.BegDate AND M.EndDate)