Oracle SQL中的最后一个订单项

时间:2013-01-16 20:35:30

标签: sql oracle

我需要列出客户表中的列,第一个订单的日期和最后一个的所有数据,客户和订单表之间的1:N关系。我正在使用Oracle 10g。

最好的方法是什么?

TABLE CUSTOMER
---------------
id              NUMBER
name            VARCHAR2(200)
subscribe_date  DATE


TABLE ORDER
---------------
id              NUMBER
id_order        NUMBER
purchase_date   DATE
purchase_value  NUMBER

4 个答案:

答案 0 :(得分:1)

以下是一种方法,使用row_number函数,一个连接和聚合:

select c.*,
       min(o.purchase_date) as FirstPurchaseDate, 
       min(case when seqnum = 1 then o.id_order end) as Last_IdOrder,
       min(case when seqnum = 1 then o.purchase_date end) as Last_PurchaseDate,
       min(case when seqnum = 1 then o.purchase_value end) as Last_PurchaseValue
from Customer c join
     (select o.*,
             row_number() over (partition by o.id order by purchase_date desc) as seqnum
      from orders o
     ) o
     on c.customer_id = o.order_id
group by c.customer_id, c.name, c.subscribe_date

答案 1 :(得分:1)

如何将customer表加入orders表并不明显(order是Oracle中的保留字,因此您的表不能命名为order) 。如果我们假设id_order中的orders加入id中的customer

SELECT c.id customer_id,
       c.name name,
       c.subscribe_date,
       o.first_purchase_date,
       o.id last_order_id,
       o.purchase_date last_order_purchase_date,
       o.purchase_value last_order_purchase_value
  FROM customer c
       JOIN (SELECT o.*,
                    min(o.purchase_date) over (partition by id_order) first_purchase_date,
                    rank() over (partition by id_order order by purchase_date desc) rnk
               FROM orders o) o ON (c.id = o.id_order)
 WHERE rnk = 1

答案 2 :(得分:0)

我对你的字段名称感到困惑,但我会假设ORDER.id是CUSTOMER表中的id。

最早的订单日期很简单。

select CUSTOMER.*, min(ORDER.purchase_date)
from CUSTOMER
  inner join ORDER on CUSTOMER.id = ORDER.id
group by CUSTOMER.*

要获取最后的订单数据,请再次将其加入ORDER表。

select CUSTOMER.*, min(ORD_FIRST.purchase_date), ORD_LAST.*
from CUSTOMER
  inner join ORDER ORD_FIRST on CUSTOMER.id = ORD_FIRST.id
  inner join ORDER ORD_LAST on CUSTOMER.id = ORD_LAST.id
group by CUSTOMER.*, ORD_LAST.*
having ORD_LAST.purchase_date = max(ORD_FIRST.purchase_date)

答案 3 :(得分:0)

也许是这样的假设ID表中的Order字段实际上是Customer ID

SELECT C.*, O1.*, O2.purchase_Date as FirstPurchaseDate
FROM Customer C
LEFT JOIN 
(
  SELECT Max(purchase_date) as pdate, id
  FROM Orders
  GROUP BY id
) MaxPurchaseOrder 
  ON C.Id = MaxPurchaseOrder.Id
LEFT JOIN Orders O1 
  ON MaxPurchaseOrder.pdate = O1.purchase_date 
  AND MaxPurchaseOrder.id = O1.id
LEFT JOIN 
(
  SELECT Min(purchase_date) as pdate, id
  FROM Orders
  GROUP BY id
) MinPurchaseOrder 
  ON C.Id = MinPurchaseOrder.Id
LEFT JOIN Orders O2 
  ON MinPurchaseOrder.pdate = O2.purchase_date 
  AND MinPurchaseOrder.id = O2.id

sql fiddle