I have some code like this:
public void gameOverCheck() {
SQLiteDatabase database = this.getWritableDatabase();
database.execSQL("SELECT " + COL_ROLE + " COUNT");
database.close();
}
in android. And would like to count the values of COL_ROLE (which has one of two possible values (mafia, civilian)). So if the number of Mafia >= Civilian game = mafias win. If Mafias = 0, game = civilian won. I am struggling with the SQL command to do the first part, am I supposed to group the values?
Try this:
Cursor mCount= db.rawQuery("select count(*) from your_table where " + COL_ROLE + " = 'mafia'", null);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();`
Related
Sorry I don't know much about SQL syntax. Basically, I have the following columns in my table:
ID GAME DRAW NUMBER
x 0 23
x 1 34
x 0 24
x 1 35
x 1 33
I want to get the max DRAW NUMBER based on the GAME column value.
For example, if I select GAME 1, I want to get a DRAW NUMBER of 35 (i.e., highest draw number for game 1 is 35)
The best I have come up with is the following:
String table = "xxx", col = "DRAW NUMBER", game_col = "GAME";
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(table, null, col+"=(SELECT MAX("+col+") FROM " + table + " GROUP BY " + game_col + ")", null, null, null, null);
.
Also I would like to get the count of a specific game based on the GAME value.
This is what I have so far:
int game_val = 1, row_count;
String table = "xxx", game_col = "GAME";
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT COUNT(*) FROM " + table + " WHERE " + game_col + " = " + game_val + "", null);
row_count = c.getCount();
Thank you in advance!
You can use rawQuery
For specific game, just replace the 1 with a variable (edited: removed group by, not needed in this one, thanks Bae)
Cursor c = db.rawQuery("SELECT max(DRAW NUMBER) FROM xxx WHERE GAME = 1", null);
For list of all max numbers for all games
Cursor c = db.rawQuery("SELECT GAME, max(DRAW NUMBER) FROM xxx GROUP BY GAME", null);
You only need this query
Cursor cursor = db.rawQuery("SELECT MAX(DRAW_NUMBER) FROM your_table_here WHERE GAME = 1, null);
For list you can use the query that Hrusilov told you.
I have the following code...
protected long getNumQueuedChunks(boolean distinctEntries) throws Exception {
SQLiteDatabase db = null;
try {
db = dbhelper.getReadableDatabase();
String whereClause = C_STATUS + " = ? AND " + C_NUM_FAILURES + " < ?";
String[] whereArgs = new String[] {STATUS_AWAITING_PROCESSING, 10};
long count = DatabaseUtils.queryNumEntries(db, QUEUE_TABLE_NAME, whereClause, whereArgs);
return count;
}
finally {
try {
db.close();
}
catch(Exception ignore) {
}
}
}
...which works fine if I want to return the total amount of rows that match the WHERE condition.
However, I would like to only count records that have distinct/unique combinations of data across these 3 columns: C_URI, C_BYTE_START_NUM and C_NUM_BYTES.
I know I could do something like...
String[] columns = {C_URI, C_BYTE_START_NUM, C_NUM_BYTES};
String whereClause = C_STATUS + " = ? AND " + C_NUM_FAILURES + " < ?";
String[] whereArgs = new String[] {STATUS_AWAITING_PROCESSING, "10"};
Cursor c = db.query(true, QUEUE_TABLE_NAME, columns, whereClause, whereArgs, null, null, null, null);
int count = c.getCount();
...but I am hoping there is a more efficient way to perform a distinct count in this situation??
Just to add clarity, if I have this data in my table...
C_URI | C_BYTE_START_NUM | C_NUM_BYTES
1.jpg | 0 | 1024
1.jpg | 1024 | 1999
2.jpg | 0 | 500
2.jpg | 0 | 500
...the result of the distinct count should be 3.
NB - I have seen a similar requirement described here (second answer) but that doesn't help me as I am wanting to do a distinct count across 3 columns rather than just one.
The most efficient way of counting records is to let the database do this:
SELECT COUNT(*)
FROM (SELECT DISTINCT Uri,
ByteStartNum,
NumBytes
FROM QueueTable)
(With the separate subquery, it does not matter if you use DISTINCT or GROUP BY over the three columns.)
This query does not fit into the constraints of one of the helper functions like query or queryNumEntries, so you have to construct the entire SQL statement by hand:
long getNumQueuedChunks() {
SQLiteDatabase db = dbhelper.getReadableDatabase();
try {
String query = "SELECT COUNT(*) FROM " +
"(SELECT DISTINCT " + C_URI + "," + C_BYTE_START_NUM + "," + C_NUM_BYTES +
" FROM " + QUEUE_TABLE_NAME +
" WHERE " + C_STATUS + " = ?" +
" AND " + C_NUM_FAILURES + " < 10)";
String[] args = new String[] { STATUS_AWAITING_PROCESSING };
return DatabaseUtils.longForQuery(db, query, args);
} finally {
db.close();
}
}
Have you tried the SQLiteDatabase.rawQuery() method? You can put a raw SQL query in it, for example, something like:
select distinct C_URI, C_BYTE_START_NUM, C_NUM_BYTES from MyTable
The method returns a Cursor, and you can immediately get the count from the cursor object. Of course, you can specify a where clause if you want to as well. Then free up the Cursor once you got your count.
I am working with sqlite where i have fired a query with "IN" operator but its taking to much time to display data. My query is following :
String Sql_query = "select id as _id,PARTY_NAME, PARTY_ADD1 as PARTY_ADD1,PARTY_KEY,PARTY_VAT from PARTYMAST where PARTY_KEY in( Select OUTACCD from OUTLETMST where OUTSMCD = " + salesman_code + " and Party_name like '" + etsearch.getText() + "%')";
Now to reducing time to get data i have made two cursors like below :
String Sql = "select id as _id,PARTY_NAME, PARTY_ADD1 as PARTY_ADD1,PARTY_KEY,PARTY_VAT from PARTYMAST";
String Sql2 = "Select OUTACCD from OUTLETMST where OUTSMCD = " + salesman_code + " and Party_name like '" + etsearch.getText() + "%')";
Cursor c1 = dbhelper.showdata(this,Sql);
Cursor c2 = dbhelper.showdata(this,Sql2);
Now i want to merge this two cursors c1 and c1 in one cursor like c1 + c2 = main_cursor
I have merged both cursor like following code :
MergeCursor merge_cursor = new MergeCursor(new Cursor[] {
c1, c2});
But it not worked in merge_cursor i getting only data of first cursor (c1).
Is it possible ? Please guide if anybody face this type of proble
Any other way to write this query ?
Thank you in advance.
You can use Join or Union for it.
Like for an example :-
sql = sql1;
sql += " UNION "
sql += sql2;
android noob... I have two tables, with a one to many relationship between country_tbl and city_tbl, and I would like to concatenate values from city_tbl.landmark_col with GROUP_CONCAT() and INSERT all the landmark_col values as a single String into country_tbl.all_landmarks column. The SQL seems to require a nested SELECT to concatenate the landmark_col values before passing them to the country_tbl... something like:
UPDATE country_tbl
SET country_tbl.all_landmarks = (SELECT landmarks_col FROM
(SELECT country_id, group_concat(landmarks_col)
FROM city_tbl INNER JOIN country_tbl
ON country_tbl.country_id = city_tbl.country_id
GROUP BY country_tbl.country_id)
AS country_landmarks
WHERE country_tbl.country_id = country_landmarks.country_id)
WHERE
EXISTS (
SELECT *
FROM country_landmarks
WHERE country_tbl.country_id = country_landmarks.country_id
);
Not sure if nested select statements are even supported or if just too resource intensive... there must be a better way, as it seems like using rawQuery is not the best solution. Not sure if I should be creating temporary tables, using ContentProviders, or passing a cursor...?
I answered this by splitting up the long SQL query into two parts. First I created a subquery with a SQLiteQueryBuilder and ran using rawQuery to get a two column cursor with the location_id and the group_concat values for the landmark_names. I was then able to cycle through the cursor to update the country table with each of the appropriate concatenated values of all the landmark names for that country.
The query below is a tad more complicated than the question above (which I simplified before posting), only because I had to join a landmarks list table with another landmark_type table by the landmark_type_id, and my real goals was to concatenate the shorter list of landmark_type by country, not the long list of all the landmark_names by country. Anyway, it works.
public void UpdateCountryLandmarks() throws SQLException {
Cursor c = null;
String subquery = SQLiteQueryBuilder.buildQueryString(
// include distinct
true,
// FROM tables
LANDMARK_TYPE_TABLE + "," + LANDMARKS_TABLE,
// two columns (one of which is a group_concat()
new String[] { LANDMARKS_TABLE + "." + LOCATION_ID + ", group_concat(" + LANDMARK_TYPE_TABLE + "." + LANDMARK_TYPE + ",\", \") AS " + LANDMARK_NAMES },
// where
LANDMARK_TYPE_TABLE + "." + LANDMARK_ID + "=" + LANDMARKS_TABLE + "." + LANDMARK_TYPE_ID,
// group by
LANDMARKS_TABLE + "." + LOCATION_ID, null, null, null);
c = mDb.rawQuery(subquery, null);
if (c.moveToFirst()) {
do {
String locationId = c.getString(c.getColumnIndex(LOCATION_ID));
String landmarkNames = c.getString(c.getColumnIndex(LANDMARK_NAMES));
ContentValues cv = new ContentValues();
cv.put(LANDMARK_NAMES, landmarkNames);
mDb.update(COUNTRY_TABLE, cv, LOCATION_ID + "=" + locationId, null);
} while (c.moveToNext());
}
c.close();
}
Hi, I am new to android. I want to write query for join in sqlite. My code is -
public Cursor SearchCategory(SQLiteDatabase db){
//return db.query("category_master", null, "status = 'Active'", null, null, null, null);
String Category_Sql = " select category_master.*,count(*) as cnt from product_master " +
" left join category_master on product_master.category_id = category_master.category_id " +
" where category_master.status = 'Active' group by category_master.category_id having cnt > 0 ";
return db.query(Category_Sql);
}
but it generate error. Where am I wrong?
It would have helped more if you could cite the error description.
Try running the query first in Portable SQLite explorer
you can use rawQuery
db.rawQuery("Select a.column1,b.column1 FROM table1 a JOIN table2 b ON a._id=b._id", null);
it should work