Alternatives to LEAD and LAG in SQLite - android

I need to find an alternative to LAG and LEAD for finding the previous and next entry in my table in SQLite since those are not support in the version used (updating is not an option).
But I also cant use the value I order by, since it can be a date and therefore can be identical on multiple entries.
Since the table has to be sorted by date, using the ID isn't an option either.
It'd be great if someone knew an alternative way of dealing with this issue, since after more than an hour of searching and trying I am out of ideas.
Edit:
The important columns to my use case are:
_id booking_date
1 2017:11-21
3 2017:11-21
4 2017:11-21
5 2017:11-21
2 2017:11-22
6 2017:11-22
7 2017:11-22
...
_id is the primary key.
The bookings need to be sorted by date.
It is possible for multiple bookings to have the same date.
Bookings with the same date are sorted by their ids (See id 2, 6 and 7 in the give n example)
I need a way to query the entry before and after an entry by its id.
For example for _id=6 the I need a query that selects the row with _id=2 and a query that selects the row with _id=7.
Alternatively a query single query that selects both will work just as good.
I do not need you to provide an entire query, but rather an approach to this issue.

Try something like that, this retrieves previous and next id of a given record using your sort order (by date+id) - assumming that id is the primary key, you can retrieve other columns od prev-next records using these ids:
SELECT *,
(SELECT id FROM t t1
WHERE t1.booking_date < t.booking_date
OR t1.booking_date = t.booking_date AND t1.id < t.id
ORDER BY booking_date DESC, ID DESC LIMIT 1 ) prev_id,
(SELECT id FROM t t1
WHERE t1.booking_date > t.booking_date
OR t1.booking_date = t.booking_date AND t1.id > t.id
ORDER BY booking_date , ID LIMIT 1 ) next_id
FROM t
order by booking_date, id
Demo: http://www.sqlfiddle.com/#!5/17631/2
| id | booking_date | prev_id | next_id |
|----|--------------|---------|---------|
| 1 | 2017-11-21 | (null) | 3 |
| 3 | 2017-11-21 | 1 | 4 |
| 4 | 2017-11-21 | 3 | 5 |
| 5 | 2017-11-21 | 4 | 2 |
| 2 | 2017-11-22 | 5 | 6 |
| 6 | 2017-11-22 | 2 | 7 |
| 7 | 2017-11-22 | 6 | (null) |

If the table looked like this, the final select would be fairly trivial.
_id booking_date seq
1 2017:11-21 1
3 2017:11-21 2
4 2017:11-21 3
5 2017:11-21 4
2 2017:11-22 1
6 2017:11-22 2
7 2017:11-22 3
seq being the number of rows in the same booking_date with smaller id. You could create a virtual view with this structure to drive the main select.
This is a possible approach. Since you were not soliciting "an entire query", I leave it up to you how to implement this idea.

Related

How to get rows from same table with different conditions

I want to get data from same table with different conditions. I am using sqlite in android studio.
**ID Name Role**
1 Emma Manager
2 Olivia Manager
3 Ava Manager
4 Isabella Sales officer
5 Sophia Sales Officer
6 Charlotte Sales Officer
7 Mia Clerk
8 Amelia Clerk
Assume this table, I have different types of roles and different numbers of persons in a role. I want to select 2 persons from each role.
Select * from employeeTable where role = 'Manager' LIMIT 2
Select * from employeeTable where role = 'Sales officer' LIMIT 2
Select * from employeeTable where role = 'Clerk' LIMIT 2
Simply I want to join the result of these three queries.
Sorry if the childish question. And thanks in advance
With row_number() window function:
select t.id, t.name, t.role
from (
select *, row_number() over (partition by role) rn
from employeeTable
) t
where t.rn <= 2
You can also define:
partition by role order by name
or:
partition by role order by id
instead of just:
partition by role
to get specific rows in the results.
See the demo.
Results:
| ID | Name | Role |
| --- | -------- | ------------- |
| 7 | Mia | Clerk |
| 8 | Amelia | Clerk |
| 1 | Emma | Manager |
| 2 | Olivia | Manager |
| 4 | Isabella | Sales Officer |
| 5 | Sophia | Sales Officer |
Try is query and check if working:
Select * from employeeTable where role = 'Manager' LIMIT 2
UNION ALL
Select * from employeeTable where role = 'Sales officer' LIMIT 2
UNION ALL
Select * from employeeTable where role = 'Clerk' LIMIT 2

Is it possible to take column names for sqlite database as input from user in an android app?

I am creating an android app for my college faculties through which they will be able to keep and maintain the attendance of students in their lectures.
I thought of designing the database this way
Date | Student1 | Student2 | . . . . . . |. . .|. . . | Student60
In this structure each INSERT INTO statement will take 61 values, one for the date and rest for presence/absence record of 60 students.
But in this case the column headers have to be named by the user(the column header should be unique identifier for that particular student, like his roll no.). Is it possible? or am I completely on the wrong track?
Please suggest if there is a better database design alternative.
I also need to provide the users the ability to retrieve aggregate attendance % of a student.
Apologies in advance if I've asked something very basic or stupid.
This is on the wrong track. Instead, make the student's ID a primary key column, and use the other columns for storing student metadata, something like this:
Students
ID | first_name | last_name |
1 | Jon | Skeet |
2 | Gordon | Linoff |
...
Attendance
ID | SID | date | status
1 | 1 | 2017-05-24 | absent
2 | 1 | 2017-05-25 | present
3 | 2 | 2017-05-24 | present
4 | 2 | 2017-05-25 | present
Now if you wanted to find out which students were present on a given day you could use the following query:
SELECT
s.first_name,
s.last_name
FROM Students s
INNER JOIN Attendance a
ON s.ID = s.SID
WHERE a.status = 'present' AND
a.date = '2017-05-24'
Note that in practice you might use an integer (0 or 1) to store the attendance.
Towards answering your actual question, if you wanted a summary by student along with his attendance record in percent over the most recent 90 days, you could use this:
SELECT SID, 100*(SUM(CASE WHEN status = 'present' THEN 1 ELSE 0 END) / 90) AS p_attedance
FROM Attendance
WHERE date > date('now', '-90 days');
GROUP BY SID

Recursive CTE query without top level result in SQLite

I'm currently working on a recursive query on an Android SQLite database. I have a table containing assets, which can form a hierarchy by referring to parents. For example:
AssetId | ParentAssetId 1--2--5
----------------------- | |
1 | NULL | |--6--8
2 | 1 | | |
3 | 1 | | |--9
4 | 1 | |
5 | 2 | |--7
6 | 2 |
7 | 2 |--3
8 | 6 |
9 | 6 |--4--10
10 | 4
I need to find all of the descendents of a given start point, but not including the start point. For example:
1 = 2,3,4,5,6,7,8,9,10
2 = 5,6,7,8,9
6 = 8,9
I managed to get this working using the example from the SQLite page:
SQLite WITH page
WITH RECURSIVE
Child(AssetId) AS (
VALUES (1)
UNION
SELECT Assets.AssetId FROM Assets, Child
WHERE Assets.ParentAssetID = Child.AssetId)
SELECT AssetId FROM Child WHERE AssetId != 1
This works, but I'm not happy regarding the final WHERE clause to filter out the original item. Is there some other way to start the cascade without including the original item?
You could start with the children of the original item:
WITH RECURSIVE
Child(AssetId) AS (
SELECT AssetId FROM Assets WHERE ParentAssetID = 1
UNION ALL
SELECT ...
)
SELECT AssetId FROM Child
This isn't really any simpler.

Selecting from a table based on relationships which are saved in another table

My Situation
I am using SQLite on Android to store some data. This data is all in the same table, but each row can have one or more relationships to other rows in that same table. These relationships are saved in another table. Think of it like this:
In Table 1 may be a row with id 0 which has 2 children with the ids 1 and 2. Both of those children will again be saved in table 1, but in table 2 there will be a mapping for each of those children from the id 0 to their own id. The tables may look something like this:
+---------------------------+
| Table 1 |
+------+------+------+------+
| ID | .... Data .... |
+------+------+------+------+
| 0 | ... | ... | ... | <--- This would be the parent of rows 1 & 2
| 1 | ... | ... | ... | as indicated in the other table
| 2 | ... | ... | ... |
| 3 | ... | ... | ... |
+----------------------------+
| Table 2 |
+-------------+--------------+
| Parent ID | Child ID |
| 0 | 1 | <-- This means that row 0 has
| 0 | 2 | <-- 2 children with the ids 1 and 2
| 2 | 5 |
| 3 | 2 | <-- Each row can have multiple parents and/or children
What I want to do essentially is select from table 1 with some arbitrary where clause and if this where clause for example matches row 0, I also need to select the children of row 0 along with it and the children of those children and so on. Since I generally suck at explaining things let me illustrate this again:
If I were to run a select like this:
SELECT * FROM TABLE1 WHERE ...
I would get a result like this:
+------+------+------+------+
| ID | .... Data .... |
+------+------+------+------+
| 0 | ... | ... | ... |
| 3 | ... | ... | ... |
But what I would like to get is this:
+------+---------+------+------+------+
| ID | isChild | .... Data .... |
+------+---------+------+------+------+
| 0 | 0 | ... | ... | ... | <--- This row along with row 3 is what actually matches the where clause
| 1 | 1 | ... | ... | ... |
| 2 | 1 | ... | ... | ... |
| 5 | 2 | ... | ... | ... |
| 3 | 0 | ... | ... | ... | <--- This row along with row 0 is what actually matches the where clause
| 2 | 1 | ... | ... | ... |
| 5 | 2 | ... | ... | ... |
Only row 1 and 3 actually match the where clause. The order of the children is not important but they should follow right after the parent and the "isChild" column would be used to indicate whether the row is a child and to what it is a child.
Notice the third row from the top in the output above, the one with the id 2. It has 2 in "isChild" because it is a child of the row above which also is a child. You can think of the whole output above as a tree like this:
- 0
- 1 <-- 1 is a child of 0
- 2 <-- 2 is a child of 0
- 5 <-- 5 is a child of 2
- 3
- 2 <-- 2 is a child of 3
- 5 <-- 5 is a child of 2
The "isChild" column essentially tells you on which level of the tree you are.
The Problem
Up until now I had implemented this with multiple selects. I would first select the rows from table1, take the ids from each row and then select the mappings for each row from table2. With those mappings I would select the children from table1 and after that I would again look for mappings of the children in table2 and so on. It doesn't take a genius to see that this can cause huge performance problems very quickly and it indeed was pretty slow.
I have since then been trying to improve this by reducing the number of selects required but now I have hit a wall. I have implemented any sort of improvement I can think of and it works for the most part but if you are dealing with big datasets everything slows down exponentially and I don't see any other way I could improve this in code. I started thinking and came to the conclusion that if I could somehow select everything at once in the manner I described above it would solve a whole slew of problems for me.
My attempts to solve the problem so far
Since I cannot improve this further in code I have turned my attention to SQL. I have already made many unrelated improvements which resulted in great performance gains by implementing triggers to do the most common tasks like creating and deleting the mappings in table2. And I have been hoping I can also solve this problem in a similar manner.
I have tried all sorts of JOINs or UNIONs but nothing seems to work as I expect it. I have a feeling I might be going about this all the wrong way. I haven't event attempted to include a "isChild" column up until now.
This is a link to the SQLFiddle I use to test my selects
When I started working on this I foolishly thought that a simple JOIN would solve the problem but I am doubting that at this point and I am also not sure if what I want to do is even possible (in an efficient manner).
This problem has made me realise how little I know about SQL and if some SQL wizard could come along and tell me how simple the solution actually is I would very much appreciate it! (Although I suspect that the solution to my problem isn't actually that simple)
Please keep in mind that this question is talking specifically about SQLite on Android. But I tried to make this question as general as possible since it is also applicable for many other SQL implementations or operating systems.
If you have a really great answer to this question with a simple solution that blows my mind and a great explanation to go along with then I won't hesitate to reward you with a bounty.
To read the children recursively, you would have to use a recursive common table expression.
However, this was introduced in SQLite 3.8.3, so your Android device is very unlikely to support it.
You have to keep using multiple queries, or to use your own version of SQLite with the NDK.

Sql query for filtering data with WHERE clause on same column

I have to tables:
Table A
id | title
1 | toto
2 | tata
3 | titi
Table B
id | title_id | tag_id
1 | 1 | 6
2 | 1 | 16
3 | 1 | 26
4 | 2 | 6
5 | 2 | 7
6 | 2 | 16
7 | 3 | 2
8 | 3 | 1
9 | 3 | 16
(Sorry for the bad table display)
In my application I have a tag listview with checkboxes, and when the user clicks a checkbox, I want to filter the titles with the clicked checkboxes:
(E.g: if user clicks tag 16, I should have title 1, 2 and 3 displayed. But if user clicks tag with id 26 AND tag with id 16, as result I should have only title with id 1)
I thought to a query like that:
SELECT DISTINCT A.title , A.id
FROM A
INNER JOIN B
ON B.title_id = A.id
WHERE B.tag_id = 26 AND B.tag_id = 16;
but obviously the last part of the query (two AND clause on a same column) is wrong, and I do not find a query which will give me this result.
I tried this :
SELECT DISTINCT A.title , A.id
FROM A
INNER JOIN B
ON B.title_id = A.id
WHERE B.tag_id IN ( '26', '16');
but the IN clause is like a OR clause, and as result, I get all the rows for value 26 plus all the rows for value 16 (title 1, 2 and 3) and not ONLY title 1.
I absolutely need to do this with and sql query because I'm using a SimpleCursorAdapter in order retrieve the datas and to fill an other listview.
I searched for a while, but I didn't find any relevant solution. (Or maybe I typed the wrong words...)
Do you have solution for me please?
PS: I hope I've been clear. Sorry for my bad english.
Use subqueries:
SELECT DISTINCT A.title, A.id FROM A WHERE
A.id IN (SELECT DISTINCT B.title_id FROM B WHERE B.tag_id='16')
AND A.id IN (SELECT DISTINCT B.title_id FROM B WHERE B.tag_id='26')

Categories

Resources