SQL INNER JOIN没有重复

时间:2014-04-08 09:41:56

标签: sql join inner-join right-join

获取下一张桌子:

  • Column1 - OrderID - Column2的最早客户订单
  • Column2 - CustomerID - Column1中订单的客户
  • 第3列 - 订单ID - 所有 *来自Column2的客户的其他*订单 哪些没有出现在Column1

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

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

提前致谢

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
;