如何使用SUM函数一列与MAX函数的另一列(示例里面)

时间:2015-10-14 11:32:25

标签: sql sum max

例如我有数据:

 ColumnID | YEAR | SUM | Specified
----------+------+-----+-----------
 1        | 2014 | 34  |  0          -- Row with MAX(Specified)
----------+------+-----+-----------
 2        | 2014 | 45  |  0
 2        | 2014 | 67  |  1          -- Row with MAX(Specified)
----------+------+-----+-----------
 3        | 2014 | 35  |  1
 3        | 2014 | 67  |  2          -- Row with MAX(Specified)
 3        | 2014 | 23  |  0

我需要ColumnID的总和,取最大的指定列

最后我必须有34 + 67 + 67 = 168(ColumnID 1,2,3,指定0,1,2)

2 个答案:

答案 0 :(得分:0)

大多数数据库都支持ANSI标准窗口函数。这让你完全按照自己的意愿行事:

select max(sum)
from (select e.*,
             row_number() over (partition by columnID order by specified desc) as seqnum
      from example e
     ) e
where seqnum = 1;

答案 1 :(得分:0)

你也可以试试这个。

SELECT sum(eachmax) FROM
(SELECT MAX(sum) AS eachmax FROM `tbl` group by columnID) as temp

<强>输出

168