如何计算由不同项分组的结果集中的最大(列)行

时间:2013-08-29 12:14:20

标签: sql database sql-server-2008

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 Fiddle

1 个答案:

答案 0 :(得分:3)

客户最常订购的商品

查询:

<强> SQLFIDDLEExample

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 |