Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java mysql表上的操作_Java_Mysql - Fatal编程技术网

Java mysql表上的操作

Java mysql表上的操作,java,mysql,Java,Mysql,我有下面的MySQL表 ArticleId | AuthorId | Author | ArticleScore ----------|----------|--------|------------- 0 |0 |Albert |0.2 0 |1 |Bob |0.2 0 |2 |Chris |0.2 1 |0 |Albert |0.5 1

我有下面的MySQL表

ArticleId | AuthorId | Author | ArticleScore
----------|----------|--------|-------------
0         |0         |Albert  |0.2
0         |1         |Bob     |0.2
0         |2         |Chris   |0.2
1         |0         |Albert  |0.5
1         |1         |Chris   |0.5
2         |0         |Chris   |0.7
我想得到下表,其中AuthorScore是作者写的所有文章的articleScore之和除以文章数量

Table Authors

Author | AuthorScore
-------|------------
Albert | (0.2 + 0.5)/2
Bob    | 0.2
Chris  | (0.2 + 0.5 + 0.7)/3
如何使用mysql语言获取上面的表? 我可以用java编写一个循环:

for (String author: authorList){
    double sum = 0.0;
    double autScore =0.0;
    List<Double> results = em.createQuery("SELECT ArticleScore FROM Table WHERE Author ='" + author +"'").getResultList();

    for (double artScore: results){
        sum += artScore;
    }

    autScore = sum / results.size();
    Table t = new Table();
    t.setAuthor(author);
    t.setAuthorScore(autScore);
    em.persist();
}
em.flush();

但我不知道如何进行数学运算以获得行数和行数…

您应该完全在SQL中使用聚合函数执行此操作:

select author, avg(articlescore) from your_first_table group by author;

然后,您可以随心所欲地使用结果-如前所述,将结果插入到另一个表中,但我建议您只需重新运行此简单查询或创建一个视图即可。

您应该使用聚合函数在SQL中完全执行此操作:

select author, avg(articlescore) from your_first_table group by author;
然后,您可以随心所欲地使用结果——如前所述,将它们插入到另一个表中,不过我建议您重新运行这个简单的查询或创建一个视图