要查找每个客户的第一个订单,请查找每个客户的第一个订单日期,然后选择该客户下的一个或一个订单。(如果 orderdate 真的只是一个客户当天可以下多份订单的日期,那么我们选择其中一个。使用 MIN(orderid) 我们很可能会得到其中的第一个 :-)
外部加入其他订单,您就完成了。
如果你的 dbms 支持元组上的 IN 子句,你会得到一个可读性很强的语句:
select first_order.orderid, first_order.customerid, later_order.orderid
from
(
select customerid, min(first_order.orderid) as first_orderid
from orders
where (customerid, orderdate) in
(
select customerid, min(orderdate)
from orders
group by cutomerid
)
) first_order
left join orders later_order
on later_order.customerid = first_order.customerid
and later_order.orderid <> first_order.orderid
;
如果您的 dbms 不支持元组上的 IN 子句,则该语句看起来有点笨拙:
select first_order.orderid, first_order.customerid, later_order.orderid
from
(
select first_orders.customerid, min(first_orders.orderid) as orderid
from orders first_orders
inner join
(
select customerid, min(orderdate)
from orders
group by cutomerid
) first_order_dates
on first_order_dates.customerid = first_orders.customerid
and first_order_dates.orderdate = first_orders.orderdate
group by first_orders.customerid
) first_order
left join orders later_order
on later_order.customerid = first_order.customerid
and later_order.orderid <> first_order.orderid
;