1

用最简单的术语来说,如果我有一个值如下的表

x    5
x    7
y    3
v    19
x    24

我希望将 x 的所有 int 值相加,不包括 y 和 v 等

我目前有返回 x 的所有列值的工作代码(在本例中为 dateAccessed)

public ArrayList<HashMap<String, String>> searchByDate() {


    String dateAccessed = FoodDiary.dateAccessed;       

    ArrayList<HashMap<String, String>> wordList;
    wordList = new ArrayList<HashMap<String, String>>();
    SQLiteDatabase database = this.getReadableDatabase();
    //String selectQuery = "SELECT  * FROM diarys";
    String selectQuery = "diarys";
    Cursor cursor = database.query(selectQuery, new String[] { "diaryId",
            "diaryName", "diaryDate", "diaryNumber" }, "diaryDate LIKE '"
            + dateAccessed + "%'", null, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("diaryId", cursor.getString(0));
            map.put("diaryName", cursor.getString(1));
            map.put("diaryDate", cursor.getString(2));
            map.put("diaryNumber", cursor.getString(3));
            wordList.add(map);
        } while (cursor.moveToNext());
    }
    return wordList;

}

我也有返回整个列的 SUM 的工作代码

int total = 0;
    Cursor cursor = database.rawQuery("SELECT SUM(builderNumber) FROM builders", null);

    if (cursor.moveToFirst()) 
    {
        total = cursor.getInt(0);
    } while (cursor.moveToNext());
    return total;

但是,我似乎无法将两者结合起来让它们一起工作。无论我以何种方式构造游标,它总是失败。

对此的任何帮助将不胜感激

4

1 回答 1

1

如果您在一开始就对您的简单示例进行原始查询

select sum(dairyNumber) from yourtable where dairyId = 'x'

  or, if you want another column than just the sum .

select diaryName, sum(dairyNumber) from yourtable where dairyId = 'x' 

如果要将“x”的值作为参数传递,则可以使用?并提供 where 参数。

对于您的具体示例,您的原始查询应该类似于

select sum(diaryNumber) from yourtable where diaryDate like '201307%'

select diaryName, sum(diaryNumber) from yourtable where diaryDate like '201307%'

希望这可以帮助。

于 2013-07-30T20:09:25.717 回答