SQL - 从组中检索平均分数

时间:2017-03-30 16:59:14

标签: mysql sql select

我的数据库包含以下内容:

|    ID     |     UID      |     file    |    score    |    time   | 
     1    |     a827vgj28df |  jack_123  |      75     |       12:44 
     2    |     ayeskfkfjhk  | jack_999   |      5     |      12:12 
     3     |    b83759       | adam_123   |      7      |      12:12 

目标: 我试图获得一个查询,显示每个文件前缀(杰克/亚当)的平均分数

显示如下:

|  Key   |   AVG 
  jack       40 
  adam        7

3 个答案:

答案 0 :(得分:1)

您可以使用substring_index提取名称前缀。从那以后,它只是简单地使用avg

SELECT   SUBSTRING_INDEX(file, '_', 1) AS key, AVG(score)
FROM     mytable
GROUP BY SUBSTRING_INDEX(file, '_', 1)

答案 1 :(得分:0)

应该像

select SUBSTRING(file, 1, 4) as Key, AVG(score)
from table
group by SUBSTRING(file, 1, 4)

如果您分享您已经尝试过的内容,将来可能会得到更好的回复。

答案 2 :(得分:0)

您可以使用SUBSTRING_INDEX获取密钥,然后按

分组
public void saveToSharedPreferences(Context context, List<String> list){

    Set<String> set =
            list.stream()
            .collect(Collectors.toSet()); // Returns in this case a Set, if you need Iterable or Collection it is also available.

    PreferenceManager.getDefaultSharedPreferences(context) // Get Default preferences, you could use other.
            .edit()
            .putStringSet("myKey", set) // Save the Set of Strings (all trips but as Strings) with the key "myKey", this key is up to you.
            .apply();                   // When possible commit the changes to SharePreferences.
}

public void saveToSharedPreferences(Context context, List<Trip> list){
    List<String> stringList = list.stream()
            .map(Trip::getName) // This uses this method to transform a Trip into a String
                                // you could use other method to transform into String but if all you need to save is the name this suffices
                                // examples: .map( trip -> trip.getName()), .map(trip -> trip.toString()), etc. you choose how to save.
                                // It should save every state that a Trip has, so when you are reading the saved Strings
                                // you will be able to reconstruct a Trip with its state from each String.
            .collect(Collectors.toList());
    saveToSharedPreferences(context, stringList);
}