从前5个数字中提取第二个和第三个最大数字

时间:2015-02-04 18:41:22

标签: mysql excel set updates

我正在寻找UPDATE(计算SET值)现有表格的解决方案,其中包含前一个5的第2和第3大数字的总和。

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(范围,2)+ LARGE(范围,3),其中范围始终指向最后5个数字。

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

如果我需要IGNORE第一个最大数字并且只加上第二和第三大数字,我该如何使这个挑战发挥作用?

这个想法围绕着这个原则:

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

1 个答案:

答案 0 :(得分: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语句。

该查询的

p.s:Number表示您桌面上的price