首页 > 解决方案 > 从 Android 中的 sqlite 返回 sum(item_price)

问题描述

我正在尝试从数据库中的特定列中获取总和。我认为我的查询没问题,但我认为收到它有问题。请指导我正确的方式。

非常感谢你。

public static double countPrice (SQLiteDatabase db, int selectedID){
    String[] sumPrice = new String[]{"sum(item_price)"};
    String selection = "list_id =? AND item_flag =?";
    String[] selectionArgs = new String[]{String.valueOf(selectedID), String.valueOf(0)};

    Cursor c = db.query(TABLE_NAME, sumPrice, selection, selectionArgs, null, null, null);

    double result = c.getCount();
    return result;
}

标签: androidsqlitesumandroid-cursor

解决方案


您正在使用 CursorgetCount()方法,该方法将返回行数,当查询返回聚合(即总和)时,行数将为 1。

相反,您需要

  • a) 移动到光标的第一行,然后
  • b) 使用适当的 Cursorget???方法从相应列中读取/提取数据。

因此,您的代码可能是:-

public static double countPrice (SQLiteDatabase db, int selectedID){
    String[] sumPrice = new String[]{"sum(item_price)"};
    String selection = "list_id =? AND item_flag =?";
    String[] selectionArgs = new String[]{String.valueOf(selectedID), String.valueOf(0)};

    Cursor c = db.query(TABLE_NAME, sumPrice, selection, selectionArgs, null, null, null);

    Double result = 0; // default value to signify nothing extracted
    if(c.moveToFirst()) { // move to the first(only) row in the Cursor
        result = c.getDouble(0); // get the value from the first column
    }
    c.close(); // Should always close cursors when done with them
    return result; // Ok to return extracted value (or default for nothing extracted)
}

推荐阅读