Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 将前5个数字中的第二和第三大数字相加_Mysql_Excel_Set_Updates - Fatal编程技术网

Mysql 将前5个数字中的第二和第三大数字相加

Mysql 将前5个数字中的第二和第三大数字相加,mysql,excel,set,updates,Mysql,Excel,Set,Updates,我正在寻找一个解决方案来更新(计算设置值)一个现有的表,使用前5个表中第2和第3大的数字之和 ID | Price | Sum | | | (2nd + 3rd largest of the previous 5)| ------------------------------------------------------- 1 | 6 |

我正在寻找一个解决方案来更新(计算设置值)一个现有的表,使用前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中,可以通过:=大(范围2)+大(范围3),其中范围始终指向最后5个数字

我知道MYSQL有两个函数:最大值(value1,value2,…)和最小值(value1,value2,…),但这个函数只返回最大值或最小值

如果我需要忽略第1大数字,而只将第2大和第3大数字相加,那么我该如何应对这一挑战

该思想围绕以下原则:

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
此查询使用前5个ID中的
(第二大+第三大)更新表中的
SUM
。但如果您想只查看结果而不进行更新,只需删除
update
语句即可


p、 s:
Number
在该查询中表示表中的
price

是否
ID
type=Number并始终按顺序?是的,ID=int并始终按顺序。谢谢你,鲁巴哈姆,现在将尝试一下。效果非常好!!你的代码是灵活的,符合我的所有标准!!!竖起大拇指!!谢谢,很高兴我能帮助你@Stan。