创建SQL查询以从两个表中检索数据

时间:2010-01-15 11:42:03

标签: sql oracle

我有两张桌子:

T_STOCK:主键是idseller,其他一些字段可以说abT_FLOW:主键是(id + startdate),还有其他一些字段,例如cd

我想要一个查询,该查询返回T_STOCK关于特定seller的每个记录的所有列,但是已经完成了列startDatec和{{ 1}})来自d表。

T_FLOWT_STOCK之间的关系基于T_FLOW属性。 每次id中都存在具有特定ID的记录时,T_STOCK中至少有一条记录存在此ID。

但是,T_FLOW中可能存在多条记录。在这种情况下,我必须只考虑最近的(即T_FLOW的那个)。

换句话说,如果我们有以下表格内容:

max(startDate)

查询结果必须是:

+---------------------+
|       T_STOCK       |
+----+--------+---+---+
| ID | SELLER | a | b |
+----+--------+---+---+
| 01 | foobar | 1 | 2 |
+----+--------+---+---+
| 02 | foobar | 3 | 4 |
+----+--------+---+---+
| 03 | foobar | 5 | 6 |
+----+--------+---+---+

+---------------------------+
|           T_FLOW          |
+----+------------+----+----+
| ID |  StartDate |  c |  d |
+----+------------+----+----+
| 01 | 01/01/2010 |  7 |  8 |
+----+------------+----+----+
| 02 | 01/01/2010 |  9 | 10 |
+----+------------+----+----+
| 02 | 07/01/2010 | 11 | 12 |
+----+------------+----+----+
| 03 | 03/01/2010 | 13 | 14 |
+----+------------+----+----+
| 03 | 05/01/2010 | 15 | 16 |
+----+------------+----+----+

我如何编写查询呢?

4 个答案:

答案 0 :(得分:3)

SELECT  *
FROM    t_stock s
JOIN    (
        SELECT  f.*, ROW_NUMBER() OVER (PARTITION BY id ORDER BY startDate DESC) AS rn
        FROM    t_flow f
        ) f
ON      f.id = s.id
        AND f.rn = 1

这是一个不使用分析函数的解决方案:

SELECT  *
FROM    t_stock s
JOIN    t_flow f
ON      (f.id, f.startDate) =
        (
        SELECT  id, MAX(startDate)
        FROM    t_flow fi
        WHERE   fi.id = s.id
        GROUP BY
                id
        )

答案 1 :(得分:1)

您可以使用分析as shown by Quassnoi或使用以下内容获取最新的T_FLOW记录:

select id, max(startdate) last_start_date from t_flow group by id;

然后,您可以将其与T_STOCK表连接 - 例如:

select
    s.*,
    f.*
from
    t_stock s
        inner join t_flow f on
                f.id = s.id
            and (f.id, f.startdate) in
                (
                select
                    id,
                    max(startdate) laststartdate
                from
                    t_flow
                group by
                    id
                )

答案 2 :(得分:0)

SELECT  DISTINCT
        s.*
       ,FIRST_VALUE(f.startdate)
        OVER (PARTITION BY f.id ORDER BY f.startdate DESC) startdate
       ,FIRST_VALUE(f.c)
        OVER (PARTITION BY f.id ORDER BY f.startdate DESC) c
       ,FIRST_VALUE(f.d)
        OVER (PARTITION BY f.id ORDER BY f.startdate DESC) d
FROM    t_stock s, t_flow f
WHERE   f.id = s.id

答案 3 :(得分:0)

select id, max(startdate) last_start_date from t_flow group by id;

然后,您可以将此加入T_STOCK表格,如下所示:

select s.*, f.* from t_stock s inner join t_flow f on f.id = s.id
and (f.id, f.startdate) in (select id, max(startdate) laststartdate
                from t_flow group by id)