我似乎无法在同一查询中使用SUM(*)和MAX(*)

时间:2018-01-11 08:34:28

标签: mysql

我要做的是基本上有一个基于两列的3列表。

id, value
----------  
1,  7
1,  1 
2,  6 
3,  9
3,  2
4,  2

我想从[上方] ...... [/ p>] [下方]

 id, sum_of_strength, max_of_strength
 ---------------------------------------
  1, 8,               11
  2, 6,               11 
  3, 11,              11
  4, 2,               11

以下是我当前正在玩的内容,但max_valuesum_value相同...有没有人知道是否有办法执行此操作。我尝试了很多其他解决方案但没有任何效果。

SELECT 
    sum_table.id,
    sum_table.sum_value,
    (SELECT MAX(sum_table.sum_value) AS max_value) AS max_value
FROM (
    SELECT
        original_table.id,
        CAST(SUM(original_table.value) AS UNSIGNED) AS sum_value
    FROM original_table
    GROUP BY original_table.id
) AS sum_table
GROUP BY sum_table.id;

1 个答案:

答案 0 :(得分:2)

You can use a subquery to get the max value:

SELECT id,
       CAST(SUM(value) AS UNSIGNED) AS sum_value,
       (SELECT CAST(SUM(value) AS UNSIGNED) AS s
        FROM original_table
        GROUP BY id
        ORDER BY s DESC 
        LIMIT 1) AS max_value
FROM original_table
GROUP BY id

Grouping has to be applied twice:

  • The main query uses it to get the sum of value per id
  • The subquery uses it to get the maximum sum among all ids

Demo here