2016-03-06 159 views
0

我有如下表:MySQL的平均

+----+----------+----------+----------+ 
| id | Column1 | Column2 | Column3 | 
+----+----------+----------+----------+ 
| 1 | 1  | 2014 | 0.2  | 
| 2 | 1  | 2013 | 0.5  | 
| 3 | 2  | 2014 | 1.9  | 
| 4 | 2  | 2013 | 1.4  | 
| 5 | 2  | 2012 | 1  | 
| 6 | 2  | 2011 | 0.4  | 
| 7 | 3  | 2016 | 1.4  | 
| 8 | 3  | 2015 | 1.2  | 
| 9 | 3  | 2014 | 0.7  | 
| 10 | 4  | 2015 | 0.5  | 
+----+----------+----------+----------+ 

什麼我需要的是以下 我想平均具有相同列1值,但在該行方式的最新數據應該由0.6相乘,並因此例如
其餘0.3

其中Column1 = 1, it should output the value of 0.2*0.6+0.5*0.3 Column1 = 2, 1.9*0.6+((1.4+1+0.4)/3)*0.3 Column1 = 3, 1.4*0.6+((1.2+0.7)/2)*0.3 Column1 = 4, 0.5

編輯:如果對於一個查詢太複雜了,我很高興這樣做那更多。

+0

是否jpql有row_number或其他窗口功能? – sagi

+0

表中有行號。但我不確定窗口的功能。 – Grego

+0

您是否知道0.6 + 0.3不等於1?因此,如果有行(11,5,2015,0.5)和(12,5,2014,0.5),則項目5的加權平均值將爲0.45而不是0.5 –

回答

1

看看這裏:sqlFiddle

SELECT 
    c1, 
    avg(c3), -- this here is the average per weight 
    weight, -- this is the weight 
    avg(c3)*weight as weighted_avg -- product between the two 
FROM 
(
    SELECT 
     table1.*, 
     if(no_of_lines is null, 
      0.3,     -- the default weight for >1 lines 
      if(no_of_lines = 1 , 
       1,     -- the weight if there's only 1 line 
       0.6     -- the weight for the 1st line if there are more 
      ) 
     ) as weight 
    FROM 
     table1 
    Left join 
    (
     select min(id) as id, count(id) as no_of_lines ,c1 
     from table1 
     group by c1 
    ) tmp on tmp.id = table1.id 
) final 
group by c1, weight 
order by c1 ASC, weight DESC 

將輸出這樣的:

c1 | avg(c3) | weight | weighted_avg 
------------------------------------ 
1 | 0.2  | 0.6 | 0.12 
1 | 0.5  | 0.3 | 0.15 
2 | 1.9  | 0.6 | 1.14 
2 | 0.9333 | 0.3 | 0.279 
3 | 1.4  | 0.6 | 0.84 
3 | 0.95 | 0.3 | 0.285 
4 | 0.5  |  1 | 0.5 

所有你現在需要做的是:

SELECT c1, sum(weighted_avg) FROM `that_select` 
GROUP by c1 

免責聲明:
1)本大概可以簡化一下,但這是的另一個故事 2)刪除評論 - 可能會給你錯誤

+0

請參閱sqlFiddle的早期版本。最後一個是/ 15。請參閱http://sqlfiddle.com/#!9/eeb9f3/10此版本不預先計算每個重量的平均值。 –