mysql 部分行 平均值_MySQL如何获取平均值的特定范围内的值

bd96500e110b49cbb3cd949968f18be7.png

I have the following table data:

value

1

5

10.5

12

36

I want to map these values into:

range avg

0-21 (1 + 5 + 10.5 + 12) / 4

21.001-34 0

34.001-64 36

64 + 0

Basically map each value to ranges and calculate the avg of all values in each range.

I tried to do:

select

case

when avggeneral between 0 and 21 then ' 0-21'

when avggeneral between 21.00001 and 34 then ' 21-34'

when avggeneral between 34.00001 and 64 then ' 34-64'

else '64+'

end as 'range',

AVG(*) as 'avg'

from table

but this doesn't work... I don't know how to make the static ranges...

How can I do that in MySQL?

Methology should be:

1. Map values into these groups ( 0-21, 21-34 etc..)

2. calulate AVG in each group.

Desired output for above example is this:

range avg

0-21 7.125

21.001-34 0

34.001-64 36

64 + 0

The range column is static. Always with 5 rows.

The avg column is dynamic.. the values there are the actual AVGs of value column.

解决方案

You could build a list of ranges using UNION ALL and LEFT JOIN with it:

SELECT CONCAT(IFNULL(ranges.min, '∞'), '-', IFNULL(ranges.max, '∞')) AS `range`, avg(value) AS avg

FROM (

SELECT 0 AS min, 21 AS max UNION ALL

SELECT 21, 34 UNION ALL

SELECT 34, 64 UNION ALL

SELECT 64, NULL

) AS ranges

LEFT JOIN t ON (ranges.min IS NULL OR value >= ranges.min) AND

(ranges.max IS NULL OR value < ranges.max)

GROUP BY ranges.min, ranges.max

Note that the above query will put 20.9999 inside [0-21) and 21.0000 inside [21-34) range.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值