sql >> Database >  >> RDS >> Mysql

Bereken (sum,max,avg) door komma's gescheiden kolom in mysql

Ik weet niet welke applicatie je ontwerpt, maar ik denk dat het een slecht ontwerp was om waarden in komma's gescheiden op te slaan in plaats van een tabeldetails te maken. Je kunt dit oplossen zonder eigenlijk een mysql-functie te gebruiken. Eerst moet u convert comma separated columns into rows en dan kun je een rekensommetje maken. Deze vraag kan u helpen:

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

De resultaten zouden als volgt moeten zijn:

id     max     min      sum      avg
--------------------------------------
1      1       9        23        4,6
2      8       2        19        4,75
3      9       1        33        5,5



  1. hoe te controleren of HikariCP-verbindingspooling werkt of niet in Java?

  2. De voordelen van PostgreSQL

  3. Database-automatisering met Puppet:MySQL- en MariaDB Galera-cluster implementeren

  4. (poor man's) implementatie van productaanbevelingen