0

获取下一张表:

  • Column1 - OrderID - 来自 Column2 的客户的最早订单
  • Column2 - CustomerID - 来自 Column1 订单的客户
  • Column3 - OrderID -来自 Column2 且未出现在 Column1 中的所有*Other* 客户订单

这是我的查询,我正在寻找一种应用上述规则的方法:

SELECT O1.orderid, C1.customerid, O2.Orderid 
FROM orders AS O1 
INNER JOIN customers AS C1 ON O1.customerid = C1.customerid
RIGHT JOIN orders AS O2 ON C1.customerid = O2.customerid
WHERE    O1.orderdate >= '2014-01-01' 
AND      O1.orderdate <= '2014-03-31' 
ORDER BY O1.orderid

提前致谢

4

2 回答 2

0

要查找每个客户的第一个订单,请查找每个客户的第一个订单日期,然后选择该客户下的一个或一个订单。(如果 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
;
于 2014-04-08T11:01:14.927 回答
0

不完全确定为什么要得到这样的结果,因为最早的订单将为给定客户的每个订单重复。

SELECT earliestOrders.orderid, C1.customerid, O1.Orderid 
FROM orders AS O1 
INNER JOIN customers AS C1 ON O1.customerid = C1.customerid
INNER JOIN (
    select o.customerid, min(o.OrderId) as OrderId
    from orders o
    Group by o.customerid
    ) earliestOrders
ON earliestOrders.CustomerId = C1.CustomerId
AND earliestOrders.orderid <> O1.Orderid
于 2014-04-08T09:52:35.090 回答