0

请耐心等待,我是 SQL 新手,无法解释这一点......

我有两个类似于以下的表:

test1
+------+----------+----------+-----------+
|  id  |  serial  |  t1data  |  t1date   |
+------+----------+----------+-----------+
|  1   |    a     |   ...    |  6/02/12  |
|  2   |    a     |   ...    |  6/04/12  |
|  3   |    b     |   ...    |  6/06/12  |
|  4   |    a     |   ...    |  6/08/12  |
+------+----------+----------+-----------+

test2
+------+----------+----------+-----------+
|  id  |  serial  |  t2data  |  t2date   |
+------+----------+----------+-----------+
|  1   |    a     |   ...    |  6/05/12  |
|  2   |    b     |   ...    |  6/07/12  |
|  3   |    b     |   ...    |  6/08/12  |
|  4   |    a     |   ...    |  6/09/12  |
+------+----------+----------+-----------+

我想创建一个查询来连接这两个表,以便其中的每条记录test2对应test1test2. 任何给定的序列都可以在任一表中有多个记录。

使用上面的示例,结果应如下所示:

+----------+----------+-----------+----------+-----------+
|  serial  |  t2data  |  t2date   |  t1data  |  t1date   |
+----------+----------+-----------+----------+-----------+
|    a     |   ...    |  6/05/12  |   ...    |  6/04/12  |
|    b     |   ...    |  6/07/12  |   ...    |  6/06/12  |
|    b     |   ...    |  6/08/12  |   ...    |  6/06/12  |
|    a     |   ...    |  6/09/12  |   ...    |  6/08/12  |
+----------+----------+-----------+----------+-----------+

这是我尝试过的查询,但它不起作用。

SELECT 
    t2.serial, t2.t2data, t2.t2date, t1a.t1data, t1a.t1date
FROM 
    test2 t2
JOIN 
    test1 t1a ON (t1a.serial = t2.serial AND t1a.t1date > t2.t2date)
LEFT JOIN 
    test1 t1b ON (t1a.serial = t1b.serial AND t1a.t1date < t1b.t1date)
WHERE 
    t1b.serial IS NULL

我可能在这一切都错了,但我能做些什么来完成这项工作?

4

1 回答 1

0

我不确定这是否是最好的方法,但它正在工作:

SELECT t2.serial, t2.t2data, t1.t1data, t1.t1date
FROM
  (SELECT t2.serial, t2.t2data, t2.t2date,
         (SELECT max(t1date)
            FROM test1 t1
           WHERE t1.serial = t2.serial
             AND t1.t1date <= t2.t2date) AS t1date
  FROM test2 t2) t2
  LEFT OUTER JOIN
   test1 t1 ON t2.serial = t1.serial AND t2.t1date = t1.t1date;

http://www.sqlfiddle.com/#!2/215c263/2

于 2013-02-20T04:19:42.313 回答