在mysql中计算(sum,max,avg)逗号分隔的列



我有一个名为POIN的表,其中有一个用逗号分隔值的列。我想计算用逗号分隔的每个值。看起来是duplicate的问题,因为这里已经有答案了。但是我想用单个查询来实现这个,而不是创建一个mysql函数。

这是我的表的样子:

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

实际上,我在谷歌和这个论坛上搜索了这个问题,还没有得到正确的答案。

我不知道从哪里开始。

我不知道你设计的是什么应用程序,但我认为用逗号分隔存储值而不是创建表详细信息是糟糕的设计。你可以解决这个问题,而不用使用mysql函数。首先,你需要convert comma separated columns into rows,然后你可以做一些计算。这个查询可能对您有所帮助:

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

最新更新