简体   繁体   English

对于列中的每个字符串计算平均值(第二列)

[英]For each string in column calculate average (second column)

This is a section of my dataset (for example flavours of ice cream and their ratings):这是我的数据集的一部分(例如冰淇淋的口味及其评级):

flavor味道 rating评分
cherry, apple, flower樱桃, 苹果, 花 4.0 4.0
apple, chocolate, banana苹果、巧克力、香蕉 3.0 3.0
banane, chocolate, strawberry香蕉、巧克力、草莓 4.0 4.0
cherry, banane, strawberry樱桃、香蕉、草莓 1.0 1.0

Now I want to calculate the average rating of the flavours.现在我想计算口味的平均评分。 So that I get following output:这样我就可以关注 output:

flavor味道 avg(rating)平均(评分)
cherry樱桃 2.5 2.5
apple苹果 3.5 3.5
banane香蕉 2.66 2.66
strawberry草莓 2.5 2.5
chocolate巧克力 3.5 3.5
flower 4.0 4.0

How can I approach this in mysql?我如何在 mysql 中解决这个问题?

with recursive u as
(select 1 as n
union all select n + 1 from u
where n < (select max(length(flavor) - length(replace(flavor, ',', ''))) + 1 
from ice_cream)),
v as
(select
  LTRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(ice_cream.flavor, ',', u.n), ',', -1)) 
single_flavor,
ice_cream.rating
from
  u inner join ice_cream
  on CHAR_LENGTH(ice_cream.flavor)
  -CHAR_LENGTH(REPLACE(ice_cream.flavor, ',', ''))>=u.n-1
)
(select single_flavor, avg(rating) from v group by single_flavor);

u gets you a table with the numbers 1, 2, ..., max number of single flavours in a row. u给你一张桌子,上面有数字 1, 2, ..., 单口味的最大数量。 v makes use of u to split every row in the original table into single flavours and their rating, and the last cte just groups rows from v by single flavour and calculates the average rating for each flavour. v利用u将原始表中的每一行拆分为单一风味及其评分,最后一个 cte 只是按单一风味v中的行进行分组,并计算每种风味的平均评分。

Fiddle 小提琴

You can use the following query您可以使用以下查询

select flavor,avg(rating)
from 
 
  (select
    tablename.rating,
    SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.flavor, ',', numbers.n), ',', -1) flavor
  from
    (select 1 n union all
     select 2 union all select 3 union all
     select 4 union all select 5) numbers INNER JOIN tablename
    on CHAR_LENGTH(tablename.flavor)
       -CHAR_LENGTH(REPLACE(tablename.flavor, ',', ''))>=numbers.n-1) t

group by flavor

Demo in db<>fiddle db<>fiddle中的演示

Take a look at this link SQL split values to multiple rows看看这个链接SQL 将值拆分为多行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM