SQLite android按名称计算

时间:2016-05-19 09:27:19

标签: android sqlite

我有一个历史记录表。

历史记录表有3列

ID   |  timestamp   | imagename

我需要计算所有图像,其名称就像我从我的应用程序转发的名称

例如

1 | 12.12.2019 | 88801

2 | 11.11.2019 | 88802

3 | 13.1.2019  | 88802

4 | 1.2.2015   | 88801

5 | 7.8.2019   | 88801

我需要这样的结果

Image name|  number of images

8801  | 3

8802  | 2

...

我需要通过转发变量imageName计算它。

这就是我现在所拥有的

 public List<HistoryLog> getAllHistoryLogsForListView(String imageName) {
        List<HistoryLog> historyLogList = new ArrayList<>();
        // Select All Query ORDER BY Timestamp | SORT ASC | LIMIT 150 rows

        String selectQuery = "SELECT  * FROM " + TABLE_HISTORY + " ORDER BY " + KEY_TIMESTAMP + " ASC " + " LIMIT 150";


        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                HistoryLog historyLog = new HistoryLog();
                historyLog.setId(Integer.parseInt(cursor.getString(0)));
                historyLog.setTimeStamp(cursor.getString(1));
                historyLog.setImageName(cursor.getString(2));

                // Adding history logs to list
                historyLogList.add(historyLog);
            } while (cursor.moveToNext());
        }

        db.endTransaction();

        // return history logs list
        return historyLogList;
    }

2 个答案:

答案 0 :(得分:2)

使用GROUP BY

SELECT imagename, count(*) FROM History GROUP BY imagename;

然后您可以从光标获取每个图像的计数:

final Map<Integer, Integer> imageCount = new HashMap<>();
// where key is imagename (int) and value is count (int)
if (c.moveToFirst()) {
    do {
        imageCount.put(
            c.getInt(0),
            c.getInt(1)
        );
    } while (c.moveToNext());
}

答案 1 :(得分:0)

从IMIST_NAME的HISTORY_TBL GROUP中选择IMAGE_NAME,COUNT(IMAGE_NAME)