哪款手机每年销量都很高?

时间:2017-04-14 20:17:39

标签: mysql sql

我在mysql中有一个表。如何编写查询以查找销售额最高的电话名称(每年的Sold_out数量最多)

--------------------------------------------
Phone      Sold_out      Month      Year
--------------------------------------------
iphone      3            Jan-15     2015
iphone      10           Feb-15     2015
samsung     4            March-15   2015
Lava        14           June-16    2016
Lenova      8            July-16    2016
Lenova      10           Sep-16     2016 
Motorola    8            Jan-17     2017
Nokia       7            Jan-17     2017
Nokia       3            Feb-17     2017
--------------------------------------------

我需要的结果是

-----------------------------
year      Phone      sales
-----------------------------
2015      iphone     13
2016      lenova     18
2017      Nokia      10
-----------------------------

1 个答案:

答案 0 :(得分:-1)

在派生表中,总销售额按(年,电话)组合计算。计算总销售额后,应确定每年的所有顶行(按销售额排名= 1)。通过使用相关子查询和having子句,从每个组(年)中识别第一行并显示为最终输出。

SELECT year,phone, sales_per_year
  FROM
      (
      SELECT year,phone,SUM(sold_out) AS sales_per_year
        FROM sales
      GROUP BY year,phone          
      ) o
 GROUP BY year,phone
 HAVING (
           SELECT COUNT(*)
             FROM 
                   (
                      SELECT year,phone,SUM(sold_out) AS sales_per_year
                        FROM sales
                      GROUP BY year,phone                          
                    ) i  
           WHERE i.year = o.year             
             AND i.sales_per_year > o.sales_per_year 
          ) < 1          
ORDER BY year,phone,sales_per_year DESC         

检查sql小提琴链接 http://sqlfiddle.com/#!9/ff096e/14