我正在寻找一个更新(计算集合值)的解决方案,一个现有的表,与前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( range ,2)+LARGE(range,3)完成,其中范围总是指向最后5个数字。
我知道MYSQL拥有最大的功能(value1,value2,.)最小值(value1,value2,.),但是这个函数只返回最大值或最小值。
如果我需要忽略第一大数字而只加到第二和第三大,我该如何使这个挑战发挥作用呢?
这一思想围绕着这个原则:
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发布于 2015-02-04 20:42:00
你可以试试这个。希望这是你想要的。
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使用update在您的表上使用(2nd Greater + 3rd Greater) from 5 previous ID查询SUM列。但是,如果只想查看结果而不进行更新,只需删除UPDATE语句即可。
p.s :查询上的Number表示表上的price。
https://stackoverflow.com/questions/28328936
复制相似问题