Oracle sql根据最大时间检索记录

时间:2012-12-17 19:27:12

标签: oracle plsql plsqldeveloper

我有以下数据。

table A

id   

1

2

3

table B

id       name      data1        data2     datetime

1        cash      12345.00                12/12/2012 11:10:12

1        quantity   222.12                  14/12/2012 11:10:12

1        date     20/12/2012               12/12/2012 11:10:12

1        date     19/12/2012                13/12/2012 11:10:12

1        date     13/12/2012                14/12/2012 11:10:12

1        quantity   330.10                   17/12/2012 11:10:12

我想检索一行中的数据,如下所示:

tableA.id      tableB.cash        tableB.date     tableB.quantity 

1               12345.00          13/12/2012       330.10

我想根据max(datetime)检索。

2 个答案:

答案 0 :(得分:2)

数据模型似乎很疯狂 - 将ORDER_ID加入CUSTOMER_ID是没有意义的。将日期存储在VARCHAR2列中是没有意义的。 CUSTOMERORDER之间没有任何关系是没有意义的。在ORDER表中有两行具有相同的ORDER_ID是没有意义的。 ORDER也是保留字,因此您不能将其用作表名。我最好的猜测是你需要像

这样的东西
select * 
  from customer c 
       join (select order_id, 
                    rank() over (partition by order_id 
                                     order by to_date( order_time, 'YYYYMMDD HH24:MI:SS' ) desc ) rnk
               from order) o on (c.customer_id=o.order_id)
 where o.rnk = 1

如果那不是您想要的,请(正如我在评论中多次提到的那样)发布预期的输出。

这些是我的查询和您的示例数据得到的结果(修复ORDER表的名称以使其实际有效)

SQL> ed
Wrote file afiedt.buf

  1  with orders as (
  2    select 1 order_id, 'iphone' order_name, '20121201 12:20:23' order_time from dual union all
  3    select 1, 'iphone', '20121201 12:22:23' from dual union all
  4    select 2, 'nokia', '20110101 13:20:20' from dual ),
  5   customer as (
  6    select 1 customer_id, 'paul' customer_name from dual union all
  7    select 2, 'stuart' from dual union all
  8    select 3, 'mike' from dual
  9  )
 10  select *
 11    from customer c
 12         join (select order_id,
 13                      rank() over (partition by order_id
 14                                       order by to_date( order_time, 'YYYYMMDD HH24:MI:SS' ) desc ) rnk
 15                 from orders) o on (c.customer_id=o.order_id)
 16*  where o.rnk = 1
SQL> /

CUSTOMER_ID CUSTOM   ORDER_ID        RNK
----------- ------ ---------- ----------
          1 paul            1          1
          2 stuart          2          1

答案 1 :(得分:1)

尝试类似

的内容
SELECT *
  FROM CUSTOMER c
  INNER JOIN ORDER o
    ON (o.CUSTOMER_ID = c.CUSTOMER_ID)
  WHERE TO_DATE(o.ORDER_TIME, 'YYYYMMDD HH24:MI:SS') =
    (SELECT MAX(TO_DATE(o.ORDER_TIME, 'YYYYMMDD HH24:MI:SS')) FROM ORDER)

分享并享受。