如何在sqlite数据库中获取列中所有数字的总和 [英] how to get the sum of all numbers in a column in a sqlite databse, android

查看:571
本文介绍了如何在sqlite数据库中获取列中所有数字的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能,正在尝试获取列中的所有整数并将它们求和总计。不确定该怎么做。

I have the following function and am trying to get all the integers in a column and summing them up for a total. not sure how to do this.

下面的代码不起作用,因为在测试中我在表中放置了两行,并且KEY_HITS列的数字为5和6,总数应该是11,但结果是4。

this code below is not working because for a test i put two rows in the table and the KEY_HITS column has the numbers 5 and 6, the total should be 11 but i am getting 4 as the result

 public int getTotal() {

    String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_HITS };
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
            null, null);
    int total = 0;

    int iHits = c.getColumnIndex(KEY_HITS);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        total = total + iHits;
    }
    return total;
}


推荐答案

getColumnIndex返回从零开始的给定列名称的索引;如果该列不存在,则为-1。您应该具有 c.getInt(KEY_HITS)

getColumnIndex Returns the zero-based index for the given column name, or -1 if the column doesn't exist. You should have c.getInt(KEY_HITS)

这篇关于如何在sqlite数据库中获取列中所有数字的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆