I have a table in which a particular column has a value repeated number of times. I want to calculate how many times it occur.
Let's say the database has column as "Select" repeated 5 times in the table. How do I count it?
this is the code I am using
public String getCountSelect() {
String count = "";
String selectQuery = "SELECT COUNT ( " + KEY_DEALER_NAME + " ) FROM "
+ TABLE_DEALER + " WHERE " + KEY_DEALER_NAME + " = 'Select'";
Log.e("", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Log.e("", cursor.getString(cursor
.getColumnIndex(KEY_DEALER_NAME)));
} while (cursor.moveToNext());
}
db.close();
return count;
}
try this way
String selectQuery = "SELECT " + KEY_DEALER_NAME + " FROM "
+ TABLE_DEALER + " WHERE " + KEY_DEALER_NAME + " = 'Select'";
Cursor cursor = db.rawQuery(selectQuery, null);
int total_count=cursor.getCount();
Cursor .getCount()
method returns total affected rows.
The name of the returned column is what you have written in the SELECT clause, ie, COUNT( DealerName )
. But this does not matter because you can use the column index, ie, you know this is column 0.
Anyway, a query with COUNT returns a single value, so you can use a DatabaseUtils helper function to make your code simpler.
Finally, COUNT(*)
is a little bit more efficient:
public long getCountSelect() {
SQLiteDatabase db = getReadableDatabase();
try {
String selectQuery =
"SELECT COUNT(*)" +
" FROM " + TABLE_DEALER +
" WHERE " + KEY_DEALER_NAME + " = 'Select'";
return DatabaseUtils.longForQuery(db, selectQuery, null);
} finally {
db.close();
}
}
Fire your query and it return cursor. And perform .getCount() function on cursor it gives you total value of your query.
code:-
cursor.getCount();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.