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

时间:2015-06-10 03:47:11

标签: mysql sql

我有一个名为POIN的表,并且有一个以逗号分隔的值的列。我想计算逗号分隔的每个值。这看起来很duplicate,因为它回答了here。但是我希望使用单个查询来实现这一点,而不是创建一个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

实际上,我在谷歌和这个论坛上搜索了这个,但还没有得到正确答案。我无法展示我到目前为止所尝试的内容,因为我不知道从哪里开始。

1 个答案:

答案 0 :(得分:3)

我不知道你设计的是什么应用程序,但我认为以逗号分隔存储值而不是创建表格详细信息是不好的设计。你可以在不使用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