Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 根据临近日期执行联接_Sql Server_Date_Join_Kql - Fatal编程技术网

Sql server 根据临近日期执行联接

Sql server 根据临近日期执行联接,sql-server,date,join,kql,Sql Server,Date,Join,Kql,我有以下两个表,希望根据最近的可用日期加入 我不能使用Delete/Inserts,因为我需要将其转换为KQLKusto。请帮忙 代码段: drop table if exists #table1 drop table if exists #table2 create table #table1 ([date] date, val int) create table #table2 ([date] date, discount int) insert into #table1 ([date],

我有以下两个表,希望根据最近的可用日期加入

我不能使用Delete/Inserts,因为我需要将其转换为KQLKusto。请帮忙

代码段:

drop table if exists #table1
drop table if exists #table2
create table #table1 ([date] date, val int)
create table #table2 ([date] date, discount int)

insert into #table1 ([date], val) values ('1/26/2010', 10)
insert into #table1 ([date], val) values ('1/25/2010', 9)
insert into #table1 ([date], val) values ('1/24/2010', 8)
insert into #table1 ([date], val) values ('1/24/2010', 9)
insert into #table1 ([date], val) values ('1/23/2010', 7)
insert into #table1 ([date], val) values ('1/22/2010', 10)
insert into #table1 ([date], val) values ('1/19/2010', 11)

insert into #table2 ([date], discount) values ('1/26/2010', 2)
insert into #table2 ([date], discount) values ('1/23/2010', 1)
insert into #table2 ([date], discount) values ('1/20/2010', 0)

Desired Result:
date    val date    discount
2010-01-26  10  2010-01-26  2
2010-01-23  7   2010-01-23  1
2010-01-19  11  2010-01-20  0

我得到了答案,但欢迎您提出任何有效的方法:

select * from (
Select t2.date,
t2.discount,t1.date as date2, t1.val ,row_number() over( partition by t2.date order by t1.date desc) rn
from #table2 t2
inner join #table1 t1 on t1.date <= t2.date) t
where t.rn = 1

根据问题指南,请不要发布代码、数据、错误消息等的图像-复制或在问题中键入文本。请保留图像用于图表或演示渲染错误,这些内容无法通过文本准确描述。请展示您的尝试,并告诉我们您在本网站或其他网站上发现了什么,以及为什么它不能满足您的需求。预期结果:date val date折扣2010-01-26 10 2010-01-26 2 2010-01-23 7 2010-01-23 1 2010-01-19 11 2010-01-20 0请直接对问题进行任何澄清。因此,您正在尝试将表2中的每一行匹配到表1中最近的日期是之前还是之后?如果你有两个等距的约会,那么选择较早的还是较晚的?如果两个约会等距,那么选择较早的