Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.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:从其他表获取上一条记录_Sql_Sql Server - Fatal编程技术网

SQL:从其他表获取上一条记录

SQL:从其他表获取上一条记录,sql,sql-server,Sql,Sql Server,我想从表B中获取表A中每条记录的前一条记录 为方便起见,下表为示例数据: drop table if exists #A drop table if exists #B CREATE TABLE #A(Name varchar(10), time datetime, value int) insert into #A values ('A', '2020-03-31 18:00:00', 56), ('A', '2020-03-31 19:00:00', 3), ('B', '2020-0

我想从表B中获取表A中每条记录的前一条记录

为方便起见,下表为示例数据:

drop table if exists #A
drop table if exists #B


CREATE TABLE #A(Name varchar(10), time datetime, value int)
insert into #A values
('A', '2020-03-31 18:00:00', 56),
('A', '2020-03-31 19:00:00', 3),
('B', '2020-03-31 14:00:00', 14),
('C', '2020-03-31 15:00:00', 26)


CREATE TABLE #B(Name varchar(10), time datetime, value int)
insert into #A values
('A', '2020-03-31 21:00:00', 79),
('A', '2020-03-31 17:00:00', 44),
('A', '2020-03-31 14:00:00', 76),
('B', '2020-03-31 18:00:00', 89),
('C', '2020-03-31 11:00:00', 29),
('C', '2020-03-31 08:00:00', 6)
编辑: 它应该只包括表B中的上一条记录。 很抱歉给你带来了困惑。还更改了图像和样本数据。

我想您需要:

select a.name, a.time, a.value
from #a a
union all
select b.name, b.time, b.value
from (select b.*, row_number() over (order by time desc) as seqnum
      from #b b
      where b.time < (select min(a.time)
                      from #a a
                      where a.name = b.name
                     )
     ) b
where seqnum = 1
order by name, time;

是这个版本的一个数据库。谢谢Gordon,如果表B有大约100万条记录并且还在增长,而表a有大约2000条记录,那么它会有效率吗?谢谢你的邀请solution@user1041627 . . . 你真的没有太多选择。但是索引在
b(name,time)
上,性能应该很好。嗨,戈登,有一个问题:我只想要一条以前的记录,而这条记录返回每个名字的所有以前的记录。e、 g如果[A-17:00]是完美的,但它也返回[A-16:00]和它之前的所有内容。@user1041627。我需要修正答案,因为您想要的是
b
中最新的记录,而不是最早的。@user1041627。我的编辑似乎没有进入。那里的版本现在似乎起作用了。
select a.name, a.time, a.value
from #a a
union all
select b.name, b.time, b.value
from (select b.*, 
             row_number() over (partition by b.name order by b.time desc) as seqnum
      from #b b
      where b.time < (select min(a.time)
                      from #a a
                      where a.name = b.name
                     )
     ) b
where seqnum = 1
order by name, time;