【问题标题】:Return sum(item_price) from sqlite in Android从 Android 中的 sqlite 返回 sum(item_price)
【发布时间】:2018-05-22 13:28:02
【问题描述】:

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

非常感谢您。

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;
}

【问题讨论】:

标签: android sqlite sum android-cursor


【解决方案1】:

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

相反,你需要

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

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

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)
}

【讨论】:

  • 非常感谢您的帮助,它有效,我今天学到了一些新东西,非常感谢。 =)
【解决方案2】:

您正在返回 cursor.getCount() ,它返回行数但不返回总和。 Android Cursor

使用以下代码:

Cursor cur = db.rawQuery("SELECT SUM(myColumn) FROM myTable", null);
if(cur.moveToFirst())
{

return cur.getInt(0);
}

【讨论】:

  • 您好,感谢您的回复,我尝试了double result; if(c.moveToFirst()) { result = c.getDouble(0); } return result;,但它给了我一个错误,说结果没有初始化,知道为什么吗?
  • 其实我知道为什么,我的愚蠢错误 =/,但非常感谢您的帮助 =) 感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 2017-03-27
  • 2011-05-31
  • 2019-03-03
  • 2014-06-18
  • 1970-01-01
相关资源
最近更新 更多