【问题标题】:Getting all the current effective records from a ORACLE table从 ORACLE 表中获取所有当前有效记录
【发布时间】:2015-01-07 15:20:18
【问题描述】:

我在 oracle 数据库中有两个表

表 1 表示带有字段 (id, name) 的表 1 记录例如

###############
id |  name
1  |  Chair
2  |  Table
3  |  Bed
###############

并且表 2 说 table2 字段为(id, table1_id, date, price)

##############################
id |table1_id| date     |  price
1  |  1  |  2013-09-09  |  500
2  |  1  |  2013-08-09  |  300
3  |  2  |  2013-09-09  |  5100
4  |  2  |  2013-08-09  |  5000
5  |  3  |  2013-09-09  |  10500
################################

我想要实现的是从表 2 中检索所有项目的最新价格

SQL 的结果应该是这样的

##############################
id |table1_id| date     |  price
1  |  1  |  2013-09-09  |  500
3  |  2  |  2013-09-09  |  5100
5  |  3  |  2013-09-09  |  10500
################################

我可以通过以下查询在 mysql 中运行

SELECT t2.id, t1.id, t1.name, t2.date, t2.price FROM table1 t1 JOIN table2 t2 ON (t1.id = t2.table1_id AND t2.id = ( SELECT id FROM table2 WHERE table1_id = t1.id ORDER BY table2.date DESC LIMIT 1 ));

但它在 ORACLE 中不起作用,这里我需要一个可以在两台服务器上运行且稍作修改的查询

【问题讨论】:

    标签: sql oracle11g


    【解决方案1】:

    你可以试试这个(应该在 MySQL 和 Oracle 中都可以使用):

    select t2.id, t2.table1_id, t2.dat, t2.price
    from table1 t1 join table2 t2 on (t1.id = t2.table1_id)
                   join (select table1_id, max(dat) max_date
                         from table2 group by table1_id) tmax
                   on (tmax.table1_id = t2.table1_id and tmax.max_date = t2.dat);
    

    如果 table2 中有多个价格,则此查询可能会针对相同的 table1_id 和日期返回多行,如下所示:

    ##############################
    id |table1_id| date         |  price
    1  |  1      |  2013-09-09  |  500
    2  |  1      |  2013-09-09  |  300
    

    可以将查询更改为每个 table1_id 仅检索 1 行,但应该有一些额外的要求(在上面的示例中选择哪一行)

    如果没关系,那么你可以试试这个:

    select max(t2.id) as id, t2.table1_id, t2.dat, max(t2.price) as price
    from table1 t1 join table2 t2 on (t1.id = t2.table1_id)
                   join (select table1_id, max(dat) max_date
                         from table2 group by table1_id) tmax
                   on (tmax.table1_id = t2.table1_id and tmax.max_date = t2.dat)
    group by t2.table1_id, t2.dat;
    

    【讨论】:

      【解决方案2】:

      您可以改用GROUP BY 尝试此操作,因为您不会从 table1 中检索产品名称,除了产品 ID(已经在 table2 中)

      SELECT id,table1_id,max(date),price
      FROM table2
      GROUP BY id,table1_id,price
      

      【讨论】:

      • id and price in group by 子句不会给出预期结果。
      【解决方案3】:

      this 是你想要的:

      select t2.id,t2.table1_id,t1.name,t2.pricedate,t2.price
      from   table1 t1
      join 
      (
          select id,table1_id, pricedate,price, row_number() over (partition by table1_id order by pricedate desc) rn
          from   table2
      ) t2
      on     t1.id = t2.table1_id
      where  t2.rn  = 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-20
        • 1970-01-01
        • 2010-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多