一个查询中的MAX()和SUM()

时间:2013-12-04 15:58:46

标签: mysql sql sum max

我有这张桌子

dept | amount | price
   1 |      2 | 20
   3 |      2 | 50
   4 |      3 | 10
   2 |      5 | 20
   1 |      1 | 15
   4 |      1 | 30
   4 |      6 |  5
   2 |      7 |  7
   1 |      1 | 24
   2 |      5 | 12
部门编号是部门编号 金额是一个产品的销售量。 价格是该产品的价格是多少

我怎样才能找到最畅销产品的部门。

我有这个:

SELECT dept, SUM( amount * price ) AS total
FROM table
GROUP BY dept

我需要它返回dept最高的total。 我不能使用MAX(SUM(金额*价格)),那我该怎么做?

噢,是的。这是学校作业,我可能不会使用LIMIT或ORDER BY

4 个答案:

答案 0 :(得分:3)

不使用LIMIT,您可以尝试使用HAVING:

SELECT dept,SUM(amount * price) AS total
FROM tab1
GROUP BY dept
HAVING SUM(amount * price) = (
    SELECT MAX(total)
    FROM (
      SELECT SUM(amount * price) AS total
      FROM tab1
      GROUP BY dept
      ) a
    )

sqlfiddle demo

答案 1 :(得分:1)

如果您不想使用ORDER和LIMIT。这是一个解决方案(已测试)

SELECT dept, SUM( amount * price ) AS total
FROM table
GROUP BY dept
HAVING SUM( amount * price ) = ( SELECT MAX(A.total)
                                 FROM
                                 (
                                     SELECT dept, SUM( amount * price ) AS total
                                     FROM table
                                     GROUP BY dept
                                  ) A
                                )

答案 2 :(得分:0)

您可以按总降序排序并获取第一个条目

SELECT dept, SUM( amount * price ) AS total 
FROM table 
GROUP BY dept
order by total desc
limit 1

答案 3 :(得分:0)

这将为您提供总数最高的部门:

select top 1 dept, sum(amount * price)
from table
group by dept
order by sum(amount * price) desc