获取表列的总数

时间:2013-07-21 18:24:54

标签: java android sqlite

我是Java编程的新手,所以我需要一些帮助......我正在做这个积累的事情......

就像这样..

Score             Accumulated
10                10
40                50
60                110
and so on.......

我的代码在这里......

public int accumulateScores(){

        db = this.getReadableDatabase();

        String query = "SELECT score, (SELECT sum(score) FROM "
                + TABLE_NAME+ ")" + " AS accumulated" + " FROM " + TABLE_NAME;
        Cursor cursor = db.rawQuery(query, null);

        if (cursor != null)
            cursor.moveToFirst();
            Score score = new Score(Integer.parseInt(cursor.getString(0)), cursor.getInt(1));




    }

我应该怎么做才能返回列分数的总和..提前致谢..任何帮助都将深受赞赏..

2 个答案:

答案 0 :(得分:1)

这应该以一种相当简单的方式完成您的需要,只需将rowid小于当前行的所有行求和。如果桌面上有自动递增键,您可能希望使用该键来获得更可预测的分数排序。

SELECT Score, 
   (SELECT SUM(Score) 
    FROM table_name a 
    WHERE rowid <= table_name.rowid
   ) Accumulated
FROM table_name
ORDER BY rowid

An SQLfiddle to test with

编辑:根据您的错误示例;

SELECT score, 
   (SELECT SUM(score) 
    FROM score_table a
    WHERE a.id <= score_table.id
   ) Accumulated
FROM score_table
ORDER BY id

Another SQLfiddle

答案 1 :(得分:0)

您应该多使用Google并输入此代码

SELECT SCORE, (SELECT SUM(SCORE) FROM table_name PATING 在哪里rowid&lt; = table_name.rowid )积累 FROM table_name ORDER BY rowid