在mysql中计算(sum,max,avg)逗号分隔的列 [英] Calculate (sum,max,avg) comma separated column in mysql
问题描述
我有一个名为 POIN
的表,并且有一列以逗号分隔值.我想计算逗号分隔的每个值.它看起来是 duplicate
问题,因为它已经回答了 这里.但我想使用单个查询而不是创建一个 mysql 函数来实现这一点.
I have a table named POIN
and has a column which have comma separated values. I want to calculate each values on the comma separated. It's looks duplicate
question because it has answered here. But I want to achieved this using single query instead of create a mysql function.
这是我的桌子:
id poin
------------------
1 1,5,9,3,5
2 2,4,8,5
3 4,7,9,1,5,7
想要的结果:
id max min sum avg
--------------------------------------
1 1 9 23 4,6
2 8 2 19 4,75
3 9 1 33 5,5
实际上,我在谷歌和这个论坛上搜索过这个,还没有得到正确的答案.我无法展示到目前为止我尝试过的内容,因为我不知道从哪里开始.
Actually, I searched this in Google and this forum and didn't get a correct answer yet. I can't show what I have tried so far, because I have no clue where to start.
推荐答案
我不知道您设计的是什么应用程序,但我认为以逗号分隔存储值而不是创建表详细信息是一种糟糕的设计.您实际上可以在不使用 mysql 函数的情况下解决此问题.首先,您需要将逗号分隔的列转换为行
,然后您可以进行一些计算.此查询可能对您有所帮助:
I don't know what application are you design, but I think it was bad design to store values in comma separated instead of create a table details. You can solved this without using a mysql function actually. First, you need to convert comma separated columns into rows
and then you can do some calculation. This query may help you :
select id,max(val) as max,min(val) as min,sum(val) as sum,avg(val) as avg
from(
select id,(substring_index(substring_index(t.poin, ',', n.n), ',', -1)) val
from poin_dtl t cross join(
select a.n + b.n * 10 + 1 n
from
(select 0 as n union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6
union all select 7 union all select 8 union all select 9) a,
(select 0 as n union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6
union all select 7 union all select 8 union all select 9) b
order by n
) n <-- To make this simple, Create a table with one column that has 100 rows.
where n.n <= 1 + (length(t.poin) - length(replace(t.poin, ',', '')))
order by val asc
) as c_rows -- c_rows = convert comma separated columns into rows
group by id
结果应该是这样的:
id max min sum avg
--------------------------------------
1 1 9 23 4,6
2 8 2 19 4,75
3 9 1 33 5,5
这篇关于在mysql中计算(sum,max,avg)逗号分隔的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!