Select only last inserted row per parent_id - android

Here is my sqlite table:
_ID | DATE_INSERTED | LATITUDE | LONGITUDE | TRACKER_ID | DATA
I need to get a Cursor with the last inserted row (by DATE_INSERTED) per TRACKER_ID, where LATITUDE and LONGITUDE are not equal to "0".
I'm doing it in a CursorLoader, this is where I could get:
public static CursorLoader getLoaderForLastMessages(Context context) {
String sel = MessageTable.LONGITUDE + " !=? and " + MessageTable.LATITUDE + " !=?";
String[] selArgs = {"0", "0"};
return new CursorLoader(context, GpsProvider.MESSAGE_CONTENT_URI, null, sel, selArgs, null);
}
I don't know how to select only the last row per TRACKER_ID. I guess DISTINCT and GROUP BY are good words, but I don't know how to use them correctly.
A raw SQLITE query is a good answer too, I'll adapt it to my code.
EDIT:
To clarify I need a Cursor like this:
_ID | DATE_INSERTED | LATITUDE | LONGITUDE | TRACKER_ID | DATA
3 | 23424123 | 13 | 43 | 1 | data
6 | 23563344 | 25 | 56 | 2 | data
19 | 56573473 | 37 | 12 | 3 | data
43 | 23635743 | 82 | 99 | 4 | data

You can query the Table for the last inserted RowID:
//Get the last inserted unique primary id (_id) of your table.
public int getPrimaryId() {
final String MY_QUERY = "SELECT MAX(_id) FROM " + DATABASE_TABLE0;
Cursor cur = mDb.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}
You can use this ID to specify in a query and load the results in your cursor.

Try this:
String selectQuery = "SELECT * FROM " + <TABLE_NAME> + " WHERE TRACKER_ID = \"" + <trackID> + "\" AND LATITUDE != '0' AND LONGITUDE != '0' AND DATE_INSERTED = \"" + <date>" ;
Cursor cursor = sqliteDatabase.rawQuery(selectQuery, null);
if(cursor.moveToLast()){
//Get the value here using cursor.getString(<column number>)
}

May be a Select Query like:
SELECT A._ID , A.DATE_INSERTED , A.LATITUDE , A.LONGITUDE , A.TRACKER_ID , A.DATA
FROM MY_TABLE A
JOIN
(
SELECT TRACKER_ID, MAX(DATE_INSERTED) MAX_DATE_INSERTED FROM MY_TABLE
WHERE LATITUDE <> '0' AND LONGITUDE <> '0'
) B
ON A.TRACKER_ID = B.TRACKER_ID
AND A.DATE_INSERTED = B.MAX_DATE_INSERTED

Related

Sqlite query to get next avaiable character of search text which contains in firstname or lastname

How to query sqlite database to get list of next available characters after the search keyword in two columns. for example, if the search keyword is ’and’
and let the columns be firstname and lastname :
And[y] Xyz
And[r]ew And[z]
Xyz And[o]n
Mirand[a] Lorand[e]
then i should get the characters [y,r,z,o,a,e].
I tried with substr and instr, but i couldn't write a query that looks in both first and last name and return next character in both of them.
With UNION ALL for the values from the 2 columns and by using rowid to get the correct order:
select nextchar from (
select
1 col,
rowid,
substr(firstname, instr(lower(firstname), 'and') + 3, 1) nextchar
from names
where firstname like '%and%'
union all
select
2,
rowid,
substr(lastname, instr(lower(lastname), 'and') + 3, 1)
from names
where lastname like '%and%'
) t
order by t.rowid, t.col
See the demo.
Results:
| nextchar |
| -------- |
| y |
| r |
| z |
| o |
| a |
| e |
If you want the result as a comma separated string, use group_concat():
select group_concat(nextchar) chars from (
select nextchar from (
select
1 col,
rowid,
substr(firstname, instr(lower(firstname), 'and') + 3, 1) nextchar
from names
where firstname like '%and%'
union all
select
2,
rowid,
substr(lastname, instr(lower(lastname), 'and') + 3, 1)
from names
where lastname like '%and%'
) t
order by t.rowid, t.col
)
See the demo.
Result:
| chars |
| ----------- |
| y,r,z,o,a,e |

SQLite on Android return wrong result

I'm having some troubles querying my SQLite DB from my Android APP.
This is the table I'm querying:
id | customerCode | invoiceNumber | openAmount | grossAmount
and this are the datas:
1 | 1 | 1 | -1.00 | -1.00
2 | 1 | 1 | 1.00 | 1.00
3 | 1 | 1 | 10.00 | 10.00
4 | 1 | 2 | 0.00 | 20.00
5 | 1 | 3 | 0.00 | 30.00
I'm trying to fetch only the lines which have openAmount != "0.00" and the query is:
String whereClause = MyTable.CUSTOMER_CODE + " = ? "
+ "and " + MyTable.OPEN_AMOUNT + " != \"0.00\"";
Cursor cur = mDb.query(MyTable.TABLE, null, whereClause, new String[]{customerId}, null, null, null);
The result I expect is that the query fetch the first 3 lines from my table, and this is the result I obtain if I query the DB from an external application (like SQLite Magic).
BUT... when I run the query from my Application, I obtain only the line with openAmount = -1.00.
I've tried a lot of solutions, like changing the where condition to fetch all the lines, but it seems that querying from my App not reads line 2 and 3.
I can't figure out a solution.
A little help would be appreciated.
EDIT
All columns are TEXT.
It's not relevant how I iterate trhough the
datas, in fact the cursor altready returns a wrong number of lines.
EDIT 2
I'm cycling though the result Cursor, and this is how i do it:
List<MyObject> list = new ArrayList<>();
MyObject obj;
//initialization of columnsIndex
//int idx1 = cur.getColumnIndex(columnName);
if (cur.moveToFirst()) {
do {
obj = new MyObject();
//set obj data
list.add(obj);
} while (cur.moveToNext());
}
cur.close();
Try like this:
String whereClause = MyTable.CUSTOMER_CODE + " = ? "
+ "and " + MyTable.OPEN_AMOUNT + " NOT LIKE '0.00'";
Cursor cur = mDb.query(MyTable.TABLE, null, whereClause, new String[]{customerId}, null, null, null);

group by and count with sqlite in android

I have a sqlite table in my android app and I need to count how many items have the same date. Here is a simple schema of the table:
col1 | col2 | date_item |
xx | xx | 2012-04-12|
yy | er | 2012-05-12|
... ... ...
I suppose that to count how many row has the same date i need to do the query using group by. The problemm is that if I do as follow:
Cursor cursor = db.query("table_name", new String[] {"date_item"}, null, null, "date_item", null, null);
and i return cursor.getColumnCount();. I get only 1 column. So how can i do this to have 2 columns (one for date_item and one for count)?
Thanks, Mattia

How to get Last record from Sqlite?

I have a one table question_table and one ImageButton (Back). I need to get the last inserted record from the database after clicking on the Back.
My row contains the following columns: question, optionA, optionB, optionC, optionD, and I need the data for use on my Activity. I create one method in database but it's not working.
Here is code for reference:
MySQLiteHelper.java extract:
public List<ObjectiveWiseQuestion> getLastInsertQuestion()
{
// long index = 0;
List<ObjectiveWiseQuestion>LocwiseProfileList=new ArrayList<ObjectiveWiseQuestion>();
db = getReadableDatabase();
Cursor cursor = db.query(
"sqlite_sequence",
new String[]{"seq"},
"name = ?",
new String[]{TABLE_QUESTION},
null,
null,
null,
null );
if (cursor.moveToFirst())
{
do {
ObjectiveWiseQuestion owq= new ObjectiveWiseQuestion();
owq.setQuestion(cursor.getString(2));
owq.setOptionA(cursor.getString(3));
owq.setOptionB(cursor.getString(4));
owq.setOptionC(cursor.getString(5));
owq.setOptionD(cursor.getString(6));
owq.setCorrectOption(cursor.getString(7));
LocwiseProfileList.add(owq);
} while(cursor.moveToNext());
db.close();
}
return LocwiseProfileList;
}
OnClickListner from AddQuestionActivity.java
imgBack.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View v)
{
msg();
emptyFormField();
try {
final List<ObjectiveWiseQuestion> LocWiseProfile = db.getLastInsertQuestion();
for (final ObjectiveWiseQuestion cn : LocWiseProfile)
{
db=new MySQLiteHelper(getBaseContext());
db.getWritableDatabase();
txtQuestion.setText(cn.getQuestion());
txtOptionA.setText(cn.getOptionA());
txtOptionB.setText(cn.getOptionB());
txtOptionC.setText(cn.getOptionC());
txtOptionD.setText(cn.getOptionD());
txtCorrectOption.setText(cn.getCorrectOption());
db.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}
});
Please give me some hint.
I think the top answer is a bit verbose, just use this
SELECT * FROM table ORDER BY column DESC LIMIT 1;
Try this:
SELECT *
FROM TABLE
WHERE ID = (SELECT MAX(ID) FROM TABLE);
OR
you can also used following solution:
SELECT * FROM tablename ORDER BY column DESC LIMIT 1;
To get last record from your table..
String selectQuery = "SELECT * FROM " + "sqlite_sequence";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
Here's a simple example that simply returns the last line without need to sort anything from any column:
"SELECT * FROM TableName ORDER BY rowid DESC LIMIT 1;"
I think it would be better if you use the method query from SQLiteDatabase class instead of the whole SQL string, which would be:
Cursor cursor = sqLiteDatabase.query(TABLE, allColluns, null, null, null, null, ID +" DESC", "1");
The last two parameters are ORDER BY and LIMIT.
You can see more at:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
If you have already got the cursor, then this is how you may get the last record from cursor:
cursor.moveToPosition(cursor.getCount() - 1);
//then use cursor to read values
Another option is to use SQLites LAST_VALUE() function in the following way.
Given this table:
+--------+---------+-------+
| OBJECT | STATUS | TIME |
+--------+---------+-------+
| | | |
| 1 | ON | 100 |
| | | |
| 1 | OFF | 102 |
| | | |
| 1 | ON | 103 |
| | | |
| 2 | ON | 101 |
| | | |
| 2 | OFF | 102 |
| | | |
| 2 | ON | 103 |
| | | |
| 3 | OFF | 102 |
| | | |
| 3 | ON | 103 |
+--------+---------+-------+
You can get the last status of every object with the following query
SELECT
DISTINCT OBJECT, -- Only unique rows
LAST_VALUE(STATUS) OVER ( -- The last value of the status column
PARTITION BY OBJECT -- Taking into account rows with the same value in the object column
ORDER by time asc -- "Last" when sorting the rows of every object by the time column in ascending order
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING -- Take all rows in the patition
) as lastStatus
FROM
TABLE
The result would look like:
+--------+--------------+
| OBJECT | LAST_STATUS |
+--------+--------------+
| | |
| 1 | ON |
| | |
| 2 | ON |
| | |
| 3 | ON |
+--------+--------------+
Suppose you are looking for last row of table dbstr.TABNAME, into an INTEGER column named "_ID" (for example BaseColumns._ID), but could be anyother column you want.
public int getLastId() {
int _id = 0;
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(dbstr.TABNAME, new String[] {BaseColumns._ID}, null, null, null, null, null);
if (cursor.moveToLast()) {
_id = cursor.getInt(0);
}
cursor.close();
db.close();
return _id;
}
Just simple, you can move with Cursor moveToLast(); method provides to move to the last record
cursor.moveToLast();
I wanted to maintain my table while pulling in one row that gives me the last value in a particular column in the table. I essentially was looking to replace the LAST() function in excel and this worked.
, (Select column_name FROM report WHERE rowid = (select last_insert_rowid() from report))
in sqlite, there is a table called sqlite_sequence, this table contains the table name and it's last id number (if the id is auto incremented).
So, to get the last row in a table just put :
Select * from TABLENAME where id=(SELECT * from sqlite_sequence where name ='TABLENAME')
The previous answers assume that there is an incrementing integer ID column, so MAX(ID) gives the last row. But sometimes the keys are of text type, not ordered in a predictable way. So in order to take the last 1 or N rows (#Nrows#) we can follow a different approach:
Select * From [#TableName#] LIMIT #Nrows# offset cast((SELECT count(*) FROM [#TableName#]) AS INT)- #Nrows#
Also, if your table has no ID column, or sorting by id doesn't return you the last row, you can always use sqlite schema native 'rowid' field.
SELECT column
FROM table
WHERE rowid = (SELECT MAX(rowid) FROM table);
Sometimes there is no ID column and ROWID does not help.
You may use simple query, which is universal (IMHO):
Select * from TABLE_NAME limit 1 offset ((select count() from TABLE_NAME) - 1)

How can i fetch the last value inserted into sqlite Database

I have a doubt to be clarified. How can i fetch the last value inserted into sqlite DB. I need code for that.I tried using query like this:
SELECT uname,umessage,utime FROM chatmessage ORDER BY utime DESC limit 1;
Where am i doing wrong?? I need help in this issue.
Thanks in advance.
SQLiteDatabase returns id of inserted row. You can rememember this id in some value and use it.
long lastId = db.insert(......);
if the value is last its id should be maximum
you can fire the query like this
c = db.rawQuery("SELECT uname,umessage,utime FROM tablename WHERE " +
"Id = (SELECT MAX(Id) FROM tablename ); ",null);
for last message by particular user add user id column in the message table like
id | userid | message | utime
1 | 1 | wlhf | 3:10
2 | 3 | dfhhfjh | 2:15
3 | 1 | kjfedhr | 4:00
4 | 2 | hejhe | 1:15
5 | 3 | kegekr | 3:30
6 | 1 | wlhf | 3:10
7 | 3 | dfhhfjh | 2:15
8 | 1 | kjfedhr | 4:00
9 | 2 | hejhe | 1:15
10 | 3 | kegekr | 3:30
c = db.rawQuery("
select message from table1 where
userid = 1 ; ",null);
recieve like
ArrayList<String> listMessg = new ArrayList<String>();
cursor = dbm.columnValueofCourse();
cursor.moveToFirst();
startManagingCursor(cursor);
for (int i = 0; i < cursor.getCount(); i++) {
reciv = cursor.getString(cursor
.getColumnIndex("message"));
listMessg.add(reciv_Par);
}
int sizeoflist = listMessg.size();
because in ascending order , the last index
of array list will be the last message of the user
System.out.println("THE LAST MESSAGE BY USER IS " + listMessg.et(sizeoflist -1));

Categories

Resources