总结前5个数字中第二个和第三个最大的数字

我正在寻找一个解决scheme来更新(计算SET值)一个现有的表格与前面5的第二和第三个最大的数字的总和。

ID | Price | Sum | | | (2nd + 3rd largest of the previous 5)| ------------------------------------------------------- 1 | 6 | | 2 | 1 | | 3 | 8 | | 4 | 3 | | 5 | 5 | | 6 | 9 | should be 11 | 7 | 1 | should be 13 | 8 | 6 | should be 13 | 9 | 6 | should be 11 | 10 | 9 | should be 12 | 11 | 2 | should be 15 | 12 | 4 | should be 12 | 

在EXCEL中,可以通过以下方式来实现:= LARGE(range,2)+ LARGE(range,3)其中range总是指向最后5个数字。

我知道MYSQL的函数GREATEST(value1,value2,…)和LEAST(value1,value2,…),但是这个函数只返回GREATEST或者LEAST的值。

如果我需要忽略第一个最大的数字并且只添加第二个和第三个最大的数字,我该如何使这个挑战工作?

思想围绕这个原则:

 UPDATE table SET SUM = GREATEST(2nd max price) where ID between ID-5 AND ID-1 + GREATEST(3rd max price) where ID between ID-5 AND ID-1 

你可以试试这个。 我希望这是你想要的。

 update yourtable, ( select id,sum(number) as sum from( select id,number, case id when @id then @rownum := @rownum+1 else @rownum := 1 and @id:= id end as r from( select t.id,t1.number from yourtable t join( select id,number from yourtable order by number desc ) t1 on t1.id between (t.id - 5) and (t.id - 1) where t.id > 5 order by t.id asc, t1.number desc ) t2 join (select @rownum:=0, @id:=0) as x )as t3 where r in(2,3) -- 2nd max + 3rd max. group by id )tab set yourtable.sum = tab.sum where yourtable.id = tab.id 

这个查询updateSUM (2nd Greater + 3rd Greater) from 5 previous ID 。 但是,如果你只想查看结果而不更新,只需删除UPDATE语句。

ps:该查询上的数字表示您的表上的price