每月销售额最高的客户名称

时间:2014-09-01 18:48:18

标签: mysql sql greatest-n-per-group

我有一张销售表,我从中选择了当月所有月份的总销售额,最高销售额,销售数量

        select monthname(date),sum(amt_c),MAX(amt_c) 
        from sales where  year(date)= year(now())
        group by monthname(date) ;

我还想选择购买率最高的客户,即客户对应MAX(amt_c)。

amt_c是客户完成的购买,

2 个答案:

答案 0 :(得分:2)

一种方法是过滤联接:

select  filter.mn 
,       filter.sum_sales
,       filter.max_sales
,       sales.cust
from    (
        select  monthname(date) as mn
        ,       sum(amt_c) as sum_sales
        ,       max(amt_c) as max_sales
        from    sales
        where   year(date) = year(now())
        group by
                mn
        ) filter
join    sales
on      monthname(sales.date) = filter.mn
        and sales.amt_c = filter.max_sales

有关更多方法,请浏览标记。

答案 1 :(得分:1)

select v.monthname,
       v.sum_amt_c,
       v.max_amt_c,
       count(s.amt_c) as num_of_amounts,
       group_concat(s.cust) as customers
  from (select monthname(date) as monthname,
               sum(amt_c) as sum_amt_c,
               max(amt_c) as max_amt_c
          from sales
         where date between concat(year(now()), '-01-01') and concat(year(now()), '-12-31')
         group by monthname(date)) v
  join sales s
    on v.max_amt_c = s.amt_c
   and v.monthname = monthname(s.date)
   and s.date between concat(year(now()), '-01-01') and concat(year(now()), '-12-31')
 group by v.monthname, v.sum_amt_c, v.max_amt_c
 order by month(s.date)

这类似于Andomar的答案,但它提供了以下好处:

  1. 如果您的DATE字段已编入索引(应该是),则上述查询将使用该索引。您应该在日期字段上没有应用函数的条件。 MySQL不支持基于函数的索引,因此给定年份(日期)没有索引。但是,日期可以编入索引。

  2. 按月#(1-12)对结果进行排序,但会显示月份名称。

  3. 如果同一个2+客户被绑定,这将列出所有这些客户,并且仅显示该月的一行。如果出现平局,您可能会在一个月内拥有2个,3个,4个以上的行。这是通过MySQL的GROUP_CONCAT函数完成的。

相关问题