SQL连接日期范围到目前为止:返回重复项

时间:2017-11-21 15:10:14

标签: sql sql-server

得到这样的表(A)

ID_1 | ID_2 | Date
  A  |   B  | 2014-12-31
  A  |   B  | 2015-12-31
  A  |   B  | 2016-12-31
  A  |   B  | 2017-12-31

我试图将其与此表(B)联系起来,因此我从表B中获得了表A中日期的1个相应值。如果存在重叠的日期范围,则可能是最大日期。 / p>

ID_1 | ID_2 | From_date  | To_date    | Value
  A  |   B  | 2014-05-01 | 2015-04-30 | 15 500
  A  |   B  | 2015-05-01 | 2016-02-29 | 17 000
  A  |   B  | 2016-10-03 | 2016-12-31 | 18 500
  A  |   B  | 2016-11-01 | 2016-12-31 | 35 000
  A  |   B  | 2017-09-01 | 2017-08-31 | 37 000
  A  |   B  | 2017-09-01 | NULL       | 37 500

我想得到这个:

Date        | ID_1 | ID_2 | From_date  | To_date    | Value
2014-12-31  |   A  |  B   | 2014-05-01 | 2015-04-30 | 15 500
2015-12-31  |   A  |  B   | 2015-05-01 | 2016-02-29 | 17 000
2016-12-31  |   A  |  B   | 2016-11-01 | 2016-12-31 | 35 000
2017-12-31  |   A  |  B   | 2017-09-01 | NULL       | 37 500

我使用以下代码:

select
a.Date,
a.ID_1,
a.ID_2,
b.From_date,
b.To_date,
b.Value,
from table_A a
left join table_B b on b.ID_1 = a.ID_1 and b.ID_2=a.ID_2 and a.Date>=b.From_dat and (b.To_date is null or a.Dato<=b.To_date)

目前这就是我得到的......

Date        | ID_1 | ID_2 | From_date  | To_date    | Value
2014-12-31  |   A  |  B   | 2014-05-01 | 2015-04-30 | 15 500
2015-12-31  |   A  |  B   | 2015-05-01 | 2016-02-29 | 17 000
2016-12-31  |   A  |  B   | 2016-10-03 | 2016-12-31 | 18 500
2016-12-31  |   A  |  B   | 2016-11-01 | 2016-12-31 | 35 000
2017-12-31  |   A  |  B   | 2017-09-01 | NULL       | 37 500

1 个答案:

答案 0 :(得分:-1)

just create the query,it works perfectly, it also helpful for long data in table 1 and table 2 please check---
---------------------
;with cte
as (
select a.Date,a.ID_1,a.ID_2,b.From_date,b.To_date,b.Value
from table1 a
left join
table2 b on b.ID_1 = a.ID_1 and b.ID_2=a.ID_2 and a.Date>=b.From_date and (b.To_date is null or a.Date<=b.To_date))
select  row_number()over (partition by date order by from_date desc )row ,ID_1,ID_2,From_date,To_date,Value into ##temp from cte
select *from ##temp
where row =1

----------------------
pls comment your result
---------