根据其他2个表选择一个表的最大值

时间:2016-01-15 14:46:24

标签: sql oracle select

我有3张桌子

Orders (orderID, CustomerID)
Orderlines (orderID, ProdID) 
Products (ProdID, CategoryID)!

我想找到最具不同的" CategoryID"在一个订单!

4 个答案:

答案 0 :(得分:2)

为了帮助您,请从基本查询开始获取您的信息:

SELECT o.customer_id
      ,l.orderid
      ,COUNT(DISTINCT categoryid) category_cnt
FROM orders o 
 JOIN  orderlines l on l.orderid = o.orderid
 JOIN products p ON l.prodid = p.prodid
GROUP BY l.customner_id, l.orderid
order by COUNT(DISTINCT categoryid) desc;

一旦你看到这个问题,我们将为此添加一个分析,以显示rank()函数

SELECT o.customer_id
      ,l.orderid
      ,COUNT(DISTINCT categoryid) category_cnt
      , rank() over (order by COUNT(DISTINCT categoryid) desc) as count_rank
FROM  orders o 
 JOIN orderlines l  on l.orderid = o.orderid
 JOIN products p ON l.prodid = p.prodid
GROUP BY l.customner_id, l.orderid
order by COUNT(DISTINCT categoryid) desc;

到目前为止?好的,现在我们只需要将其推入子查询中以获得排名第一的记录(如果多个客户订单与最高计数匹配)

SELECT customer_id, order_id, category_cnt
FROM (
    SELECT o.customer_id
          ,l.orderid
          ,COUNT(DISTINCT categoryid) category_cnt
          , rank() over (order by COUNT(DISTINCT categoryid) desc) as count_rank
    FROM  orders o 
     JOIN orderlines l  on l.orderid = o.orderid
     JOIN products p ON l.prodid = p.prodid
    GROUP BY l.customner_id, l.orderid)
WHERE count_rank = 1;

答案 1 :(得分:0)

尝试;

with data_a as (    --distinct  CategoryID cnt
    select 
        o.orderID,
        o.customerID,
        count(DISTINCT p.CategoryID) cnt
    from Orders o
    join Orderlines ol.orderID = o.orderID
    join Products p on  p.ProdID  = ol.ProdID
    group by o.orderID, o.customerID
),
data as (    --get all count rnk
    select
        orderID,
        customerID,
        rank() over (partition by orderID, customerID order by cnt desc)  rnk
    from data_a
)
select
    orderID,
    customerID
from  data
where rnk = 1

答案 2 :(得分:0)

一步一步:首先计算每个订单的不同类别。然后对您的订单进行排名,以便具有最多类别的订单获得排名#1。然后找到排名第一的所有订单的客户。

select distinct cutomerid
from orders
where orderid in
(
  select orderid
  from
  (
    select orderid, rank() over (order by category_count desc) as rnk
    from
    (
      select ol.orderid, count(distinct p.distinctcategroyid) as category_count
      from orderlines ol
      join products p on p.prodid = ol.prodid
      group by ol.orderid
    ) counted
  ) ranked
  where rnk = 1
);

答案 3 :(得分:-1)

像我猜的那样

SELECT o.customerID, t.category_cnt 
  FROM (SELECT l.orderid, COUNT(DISTINCT categoryid) category_cnt
          FROM orderlines l
          JOIN products p ON l.prodid = p.prodid
          GROUP BY l.orderid
         ORDER BY category_cnt DESC) t
  JOIN orders o ON o.orderid = t.orderid
 WHERE rownum < 2