简体   繁体   中英

Linq to Join tables based on date in between

CREATE Table A
(StartDate DATETIME, 
EndDate DATETIME,
Price float)

CREATE Table B
(EfectiveDate DATETIME,
Item VARCHAR(50))

INSERT INTO A values ('01/20/2016', '11/12/2017', '2.40')
INSERT INTO A values ('11/13/2017', '03/02/2019', '1.20')
INSERT INTO A values ('03/03/2019', '05/22/2019', '2.20')
INSERT INTO A values ('05/23/2019', '07/23/2019', '1.90')

INSERT INTO B values ('06/21/2019' 'Pen')
INSERT INTO B values ('01/01/2018','Pencil')

I need to combine these 2 tables unsing LINQ based on the effective date in table B should be in between StartDate and EndDate in table A

Something like ...

Select * FROM B
INNER JOIN A on B.EfectiveDate BETWEEN A.StartDate AND A.EndDate

OR

from tblB in B 
join tblA in A on tblB.B.EfectiveDate BETWEEN tblA.StartDate AND tblA.EndDate

Obviously my LINQ query above is wrong, but I hope you get the idea.

You can't specifically join on BETWEEN condition

you can try to use a cartesian product and then filter on the appropriate conditions:

from tblB in B
from tblA in A
where tblB.EfectiveDate >= tblA.StartDate && tblB.EfectiveDate <=  tblA.EndDate
select new {
    StartDate = tblA.StartDate,
    EndDate = tblA.EndDate,
    Price = tblA.Price,
    EfectiveDate = tblB.EfectiveDate,
    Item = tblB.Item
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM