如何选择每月最大消费客户

时间:2015-10-30 05:15:47

标签: mysql sql

我有一个列出date,customerID,orderID和orderCost的视图。 如何选择每月最高消费客户? 该数据仅在2015年持续六个月。

我能够每个月获得每个客户花费的SUM,而不是最大消费客户:

SELECT EXTRACT(YEAR FROM date) AS year, MONTHNAME(date) AS month, customerID, SUM(orderCost) 
FROM CustomerPricedOrder 
GROUP BY MONTH(date), customerID;

*其中CustomerPricedOrder是一个从名为CustomerOrder的表中获取数据的视图

如何通过存储过程找到每月最大消费客户? 我需要光标吗?

调用程序时我需要的输出示例:

  • 年........月......... customerID
  • 2015 ........一月....... 4
  • 2015 ........二月...... 21
  • 2015 ........三月......... 6
  • 2015 ........四月......... 11

其中customerID是该月的最高消费客户。

6 个答案:

答案 0 :(得分:3)

您可以按照降序排序并限制1吗?

SELECT EXTRACT(YEAR FROM date) AS year, MONTHNAME(date) AS month, customerID, SUM(orderCost) as sum_of_order_cost FROM CustomerPricedOrder GROUP BY MONTH(date), customerID order by sum_of_order_cost desc limit 1;

答案 1 :(得分:2)

SELECT EXTRACT(YEAR FROM date) AS year, 
MONTHNAME(date) AS month, 
customerID, 
SUM(orderCost) as sum_order_cost, 
MAX(sum_of_order_cost) FROM CustomerPricedOrder 
GROUP BY MONTH(date), customerID 
order by sum_order_cost DESC
LIMIT 1

这可能有效

答案 2 :(得分:0)

亚历,

你能试试吗

SELECT EXTRACT(YEAR FROM date) AS year, MONTHNAME(date) AS month, customerID, SUM(orderCost) AS cost 
FROM CustomerPricedOrder 
GROUP BY MONTH(date), customerID ORDER BY cost DESC;

如果我的大脑正确理解这应该可以胜任。

答案 3 :(得分:0)

这是一种使用变量来模拟row_number()的方法。该查询对一组中的每个客户(每个组代表一个月)进行排名,从最高消费客户的1开始,并保留排名为1的那些客户:

SELECT * FROM (
    SELECT @rn := if(@prevMonth = month AND @prevYear = year, @rn + 1, 1) rn, 
           @prevMonth := month, @prevYear := year, *
    FROM ( 
        SELECT YEAR(date) AS year, 
            MONTHNAME(date) AS month, 
            customerID, 
            SUM(orderCost) AS sum_order_cost
        FROM CustomerPricedOrder 
        GROUP BY MONTHNAME(date), YEAR(date), customerID
    ) t ORDER BY year, month, sum_order_cost desc
) t WHERE rn = 1

答案 4 :(得分:0)

试试这个......

SELECT EXTRACT(YEAR FROM date) AS year, 
MONTHNAME(date) AS month, 
customerID, 
SUM(orderCost) as sum_of_order_cost, 
MAX(sum_of_order_cost) FROM CustomerPricedOrder 
GROUP BY MONTH(date), customerID 
order by orderCost;

答案 5 :(得分:0)

似乎是分析函数的直接应用

    select year, month, customer, amount,
    rank() OVER (PARTITION BY year, month ORDER BY amount DESC) rn
    (
          SELECT EXTRACT(YEAR FROM date) AS year, MONTHNAME(date) AS month,customerID, SUM(orderCost) amount
          FROM CustomerPricedOrder 
          GROUP BY MONTH(date), customerID
    ) 

;

这会将每年/每月的金额与指定的最高金额rn -> 1进行排名。使用分析函数时需要注意的一般性问题是您希望如何处理"相同的结果" (即两个客户在一段时间内的金额相同)。检查是否需要处理这种情况以及Row_Number是否更适合您的需求(即使对于相同的结果也强制使用唯一编号,而rank()将为相同的结果分配相同的订单号),或者您需要添加到分析函数中的排序标准。