1
SELECT T1.* FROM 
(
    SELECT
        MAX(no_of_orders)   [no_of_orders], 
        ord.customer_id     [customer_id], 
        ord_dtl.item_id     [item_id]
    FROM order_main ord
    INNER JOIN order_detail ord_dtl
        ON ord.order_id = ord_dtl.order_id      
    GROUP BY 
        ord.customer_id, ord_dtl.item_id
) T1    
INNER JOIN 
(
    SELECT
        MAX(no_of_orders) [no_of_orders], 
        ord.customer_id
    FROM order_main ord
    INNER JOIN order_detail ord_dtl
        ON ord.order_id = ord_dtl.order_id
    GROUP BY 
        ord.customer_id
) T2
ON 
    T1.customer_id = T2.customer_id
    AND T1.no_of_orders = T2.no_of_orders

我从表 order_main 和 order_detail 中计算了客户订购次数最多的商品。

我所做的就像我计算了按客户 ID 和项目 ID 分组的订单数量,并将结果集减少为客户订购的最多项目,我通过相同的查询加入了结果集,删除了按项目 ID 分组。

我不觉得这是一个很好的查询。

有更好的选择吗?

SQL小提琴

4

1 回答 1

3

客户订购最多的商品

询问:

SQLFIDDLE示例

SELECT a.no_of_orders,
       a.customer_id,
       a.item_id
FROM (SELECT
        MAX(no_of_orders)   [no_of_orders], 
        ord.customer_id     [customer_id], 
        ord_dtl.item_id     [item_id],
    ROW_NUMBER() OVER(PARTITION BY ord.customer_id  ORDER BY MAX(no_of_orders) DESC) AS rnk
    FROM order_main ord
    INNER JOIN order_detail ord_dtl
        ON ord.order_id = ord_dtl.order_id      
    GROUP BY 
        ord.customer_id, ord_dtl.item_id) a
WHERE a.rnk = 1

结果:

| NO_OF_ORDERS | CUSTOMER_ID | ITEM_ID |
---------------|-------------|---------|
|           20 |           2 |       6 |
|           50 |           7 |       6 |
|         1500 |           8 |       7 |
|           10 |           9 |       3 |
于 2013-08-29T12:22:40.090 回答