我有下表:
+----+----------+----------+----------+
| 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 |
+----+----------+----------+----------+
我需要的是以下内容 我想平均具有相同Column1值的行,但最新数据应该乘以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 :(得分: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)删除评论 - 可能会给你错误