gpt4 book ai didi

MySQL 一些具有特殊权重的行的平均值

转载 作者:行者123 更新时间:2023-11-29 11:40:42 26 4
gpt4 key购买 nike

我有下表:

+----+----------+----------+----------+
| 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

编辑:如果这对于一个查询来说太复杂,我也很乐意使用更多查询。

最佳答案

在这里查看: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) 删除注释 - 可能会给您带来错误

关于MySQL 一些具有特殊权重的行的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35825115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com