2016-01-15 100 views
0

選擇一個表中的最大值,我有3個表取決於其他2臺

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

我想找到它在一個秩序的最不同的「類別ID」在客戶!

+0

您能否提供示例SQL你嘗試過這一刻? –

+0

可以玩玩具舉例嗎? – Paul

+0

我沒有想到的東西試試這就是爲什麼我問!我不知道如何開始! –

回答

-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 
+0

我會試試看! –

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 
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 
); 
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; 

一旦你看到這個作品的時候,我們將一個分析添加到該向你展示的排名( )功能

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; 
+0

很好的解釋和一個不錯的緊湊查詢。你在'rank()中錯過了'by'(按COUNT排序)。 –

+0

修正 - 感謝你注意到。總是有趣的編寫代碼而無法測試它:) –