0

Sample data

+----+------------+-------+------------+
| ID | first_name | sales | sale_date  |
+----+------------+-------+------------+
|  1 | Lindsey    | 32.02 | 2007-03-12 |
|  2 | Nicole     | 26.53 | 2007-03-12 |
|  3 | Britney    | 11.25 | 2007-03-12 |
|  4 | Ashley     | 18.96 | 2007-03-12 |
|  5 | Lindsey    |  9.16 | 2007-03-11 |
|  6 | Nicole     |  1.52 | 2007-03-11 |
|  7 | Britney    | 43.21 | 2007-03-11 |
|  8 | Ashley     |  8.05 | 2007-03-11 |
|  9 | Lindsey    | 17.62 | 2007-03-10 |
| 10 | Nicole     | 24.19 | 2007-03-10 |
| 11 | Britney    |  3.40 | 2007-03-10 |
| 12 | Ashley     | 15.21 | 2007-03-10 |
| 13 | Lindsey    |  0.00 | 2007-03-09 |
| 14 | Nicole     | 31.99 | 2007-03-09 |
+----+------------+-------+------------+

I try to find biggest total sales produce by any of this girl

I can find the biggest total sales by using this query

select first_name, sum(sales) as total 
   from cookie_sales 
   group by first_name 
   order by total desc limit 1;

I wonder is there a way to find same value using aggregate max function
If i using something like this

select first_name, max(sum(sales)) from cookie_sales group by first_name;

I will get 1111 Mysql error (Invalid use of group function )

Is there a way?

4

4 回答 4

0

您最初在问题中编写的查询可能是最好的方法。我不明白那会有什么问题。这里不需要使用子查询。

于 2013-07-18T19:45:36.467 回答
0

您可以尝试创建一个视图,然后在其上尝试 MAX。像这样的东西:

CREATE VIEW sales_sums AS
select first_name, sum(sales) as total 
   from cookie_sales 
   group by first_name 
   order by total desc limit 1;


SELECT first_name, MAX(total ) AS max_total
FROM sales_sums
GROUP BY first_name
于 2013-07-18T19:34:50.677 回答
0

您可以通过这种方式使用 MAX 函数:

SELECT MAX(sum_sales)
FROM (
  SELECT first_name, SUM(sales) sum_sales
  FROM cookie_sales
  GROUP BY first_name
) s

但是,如果您还需要获取 first_name,则此查询将比您的原始查询复杂一些。

于 2013-07-18T19:35:44.280 回答
0

有一种方法; 您需要使用足够新的 MySQL 版本来支持子查询(应该是 5.0 或更高版本):

SELECT first_name, MAX(total) FROM 
  (SELECT first_name, SUM(sales) AS total
   FROM cookie_sales
   GROUP BY first_name
   ORDER BY total DESC) sum_query
GROUP BY first_name
LIMIT 0, 1;
于 2013-07-18T19:36:14.360 回答