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

标签 mysql sql jpql

我有下表:

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

相关文章:

php - 如何在提交时下载在 PHP 中同时创建的文件?

mysql - 结合INSERT和SELECT查询产生唯一的ID

hibernate - JPA:跨两个持久性单元连接

java - QueryDSL JPA- 与 group by 无关的自连接

php - 如何确保在 PHP 中作为一个单元提交或中止 SQL 操作?

mysql - Laravel 选择左连接查询

SQL:条件选择中的条件选择

c# - 数据库失败 db = DatabaseFactory.CreateDatabase();

java - 将参数设置为 IN 表达式的列表

php - 使用显示为 onclick/checkbox id 的 MySQL id