2015-02-04 33 views
1

我要尋找一個解決方案來更新(計算設定值)的現有表2日之前的5SUM第二和第三大號碼的開出前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 
+0

'ID' type = number並且總是順序? – RubahMalam

+0

是的,ID = int並且總是按順序。 – Stan

回答

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 

此查詢上yourtable updateSUM(2nd Greater + 3rd Greater) from 5 previous ID。但是,如果您只想查看結果而不更新,只需刪除UPDATE聲明。

p.s:Number對此查詢意味着price在您的表上。

+0

謝謝RubahMalam,現在就試試這個。 – Stan

+0

出色!你的代碼是靈活的,符合我所有的標準!豎起大拇指!! – Stan

+0

謝謝,很高興我能幫助你@Stan。 – RubahMalam