[英]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 ![]() |
apple, chocolate, banana![]() |
3.0 ![]() |
banane, chocolate, strawberry![]() |
4.0 ![]() |
cherry, banane, strawberry![]() |
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 ![]() |
apple![]() |
3.5 ![]() |
banane![]() |
2.66 ![]() |
strawberry![]() |
2.5 ![]() |
chocolate![]() |
3.5 ![]() |
flower![]() |
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
中的行进行分组,并计算每种风味的平均评分。
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.