简体   繁体   English

Linq根据日期之间的联接表

[英]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 我需要将这两个表结合起来,根据表B中的生效日期,LINQ应该在表A中的StartDate和EndDate之间

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. 显然我上面的LINQ查询是错误的,但我希望你明白这个想法。

You can't specifically join on BETWEEN condition 你不能专门加入BETWEEN条件

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
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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