所以我在MySQL数据库中有两列文本,例如:
Name Score
Henry Hodgens 4
Mary Hodgens 8
Jim Servan 2
Jane Servan 4
Hank Servan 6
Sarah Smith 10
Mary Smith 12
Henry Dobbins 2
Henry Jenkins 4
我需要使用PHP运行查询,该查询可以根据“名称”中单个单词的最常见情况显示“得分”的平均值。因此,它表明“Servan”平均为4,“Henry”平均为3.3,“Hodgens”平均为6,“Mary”平均为10,按“名称”中大多数出现的顺序排列。
我希望这是有道理的。
答案 0 :(得分:3)
这在MySQL内部很难做到。它非常适合存储和检索关系值,而不是很好地进行这种计算。如果您不介意在PHP中执行此操作,则可以使用以下代码来计算频率。
foreach ($rows as $row)
{
foreach (explode(" ", $row['Name']) as $token)
{
$total[$token] += (int)$row['Score'];
$occurances[$token]++;
}
}
// compute average by taking ($total[$token])/($occurances[$token])
答案 1 :(得分:1)
你可以这样做:
SELECT
AVG(t.Score) AS ScorceAvg,
t.name
FROM
(
SELECT
SUBSTRING(Table1.Name,1,INSTR(Table1.Name, ' ')) AS name,
Table1.Score
FROM
Table1
UNION ALL
SELECT
SUBSTRING(Table1.Name,INSTR(Table1.Name, ' ')) AS name,
Score
FROM
Table1
) AS t
GROUP BY
t.name
答案 2 :(得分:1)
这是完美的事情
SELECT distinct
SUBSTRING(NAME, LOCATE(' ',NAME)+1) as NameED,
(select
avg(score)
from avgscore
where NameED = SUBSTRING(NAME, LOCATE(' ',NAME)+1)) as Score
FROM avgscore
答案 3 :(得分:0)
试试这个
SELECT sum(Score)/count(Name) as average FROM tablename where Name regexp "Mary";