如何基于一个列的后继值选择基于另一个表的第一个表数据

时间:2018-10-16 10:22:00

标签: sql sql-server sql-server-2014

我有两个表,我需要根据一个条件从两个表中选择数据。我的表格结构是

create table Las(name nvarchar(50), Depth int);
insert into Las values('testName1', 25);
insert into Las values('testName2', 76);
insert into Las values('testName3', 31);
insert into Las values('testName4', 24);

create table Calci(name nvarchar(50), Depth int, carbon int, calcium int);
insert into Calci values('testName1', 24,30,10);
insert into Calci values('testName1', 30,25,15);
insert into Calci values('testName1', 31,24,16);
insert into Calci values('testName2', 75,25,15);
insert into Calci values('testName2', 80,24,16);
insert into Calci values('testName2', 85,28,25);

条件:根据表1的深度,选择表1的名称,深度以及表2的碳和钙柱。表2中的下一个深度。 会像这样。

Output

2 个答案:

答案 0 :(得分:3)

尝试一下,更改your_first_table和your_second_table的名称:

select t1.name,t1.Depth,q.carbon,q.calcium
from your_first_table t1
outer apply
(
    select top 1 carbon,calcium
    from your_second_table t2
    where 
        t2.name=t1.name
        and t2.Depth>t1.Depth -- From all the highest,....
    order by t2.Depth asc -- get the smaller
)q

答案 1 :(得分:0)

我会使用APPLY

SELECT t1.name, t1.Depth, t2.carbon, t2.calium 
FROM table1 t1 CROSS APPLY
     (SELECT TOP (1) t2.*
      FROM table2 t2
      WHERE t2.name = t1.name AND t2.Depth > t1.Depth
      ORDER BY t2.Depth 
     ) t2;