1

(SQL SERVER 2008)我在多个表中添加了时间戳记录以加入主/基表。时间点有时等于基表,但有时不等于。

创建表的代码:

create table base (time float);
create table table2 (time float, val2 char(1));
create table table3 (time float, val3 int);
insert into base values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
insert into table2 values (1, 'a'),(5, 'z'),(6, 'm'),(9, 'b');
insert into table3 values (1.5, 1),(5.3, 10),(5.5, 0),(8.1, 4);

结果集应该是基表中的每条记录和其他表中的“最新”值。以前,这些表在 Excel 中使用设置为 TRUE 的 Vlookup “连接”,这会从已排序的表中获取最接近的匹配项。

最终结果应如下所示:

time | val2 | val3
1  | a | NULL
2  | a | 1
3  | a | 1
4  | a | 1
5  | z | 1
6  | m | 0
7  | m | 0
8  | m | 0
9  | b | 4
10 | b | 4

如何使用 SQL 语句复制它?

因为只有大约 100 条记录在玩,所以我会在这里考虑可读性而不是效率。

4

2 回答 2

3

也许最易读的是select子句中的相关子查询:

我一般不是 inside 的粉丝selectselect但相关子查询确实模仿了 Excel vlookup 的行为。

Select
  b.time,
  (Select max(t2.val2) From table2 t2 Where b.time >= t2.time) As val2,
  (Select max(t3.val3) From table3 t3 Where b.time >= t3.time) As val3
From
  base b
Order By
  b.time;    

http://sqlfiddle.com/#!3/3545e/18

(感谢 Laurence 提供上述代码和 SQL Fiddle。)

The use of max requires that the values be non-decreasing. The following version works regardless:

select
  b.time,
  (select top 1 t2.val2 from table2 t2 where b.time >= t2.time order by t2.time Desc) as val2,
  (select top 1 t3.val3 from table3 t3 where b.time >= t3.time order by t3.time Desc) as val3
from
  base b

http://sqlfiddle.com/#!6/a5148/5

于 2013-01-18T19:43:14.770 回答
2

一般原则是使用外连接来确保即使第二个表中没有匹配项也能得到结果。然后,您可以使用不等式来限制超出的任何内容,并max选择剩余的最高值。

这对于大型表可能效率低下,因为您实际上是在进行t2and的交叉连接t3。最好先做一个嵌套查询,然后再加入结果:

-- Easier to read    
Select
  b.time,
  max(t2.val2) As val2,
  max(t3.val3) As val3
From
  base b
    left outer join
  table2 t2
    on b.time >= t2.time
    left outer join
  table3 t3
    on b.time >= t3.time
Group By
  b.time
Order By
  b.time;

-- Probably faster
Select
  n.time,
  n.val2,
  Max(t3.val3)
From (
    Select
      b.time,
      Max(t2.val2) As val2
    From
      base b
        left outer join
      table2 t2
         On b.time >= t2.time
    Group By
      b.time
    ) n
    Left Outer Join
  table3 t3
    On n.time >= t3.time
Group By
  n.time,
  n.val2
Order By
  n.time;

http://sqlfiddle.com/#!3/3545e/15

于 2013-01-18T19:35:07.017 回答