How can I query a database to display a table with data by two different IDs, yet alternate each ID per row and yet still order by time. For example. Database has 10 Elements of ID1 and 10 Elements of ID2.
I need it to be:
ID1 #data #2minutes ago
ID2 #data #15minutes ago
ID1 #data #4minutes ago
ID2 #data #50minutes ago
Any Ideas?
UPDATE: The number of ID's must be able to differ from one to n and also I am currently trying to do this via the SQLite.query() method.
UPDATE 2: The #data represent columns of data within that row, not just one, so there could be 5 columns for example. Also, The data has to be returned via a cursor.
UPDATE 3: Further elaboration, below is a table and expected result I am trying to achieve.
The input table (Ordered by Time)..
id | name | number | time
01 Tim 561481 2 minutes ago
02 Jon 951484 5 minutes ago
02 Jon 978284 7 minutes ago
04 Zen 171484 15 minutes ago
04 Zen 171484 17 minutes ago
03 Ken 468488 20 minutes ago
02 Jon 978284 32 minutes ago
And the output: note, I need to alternate the Id's within the data base where possible and yet still order the whole thing by time, for example:
id | name | number | time
01 Tim 561481 2 minutes ago
02 Jon 951484 5 minutes ago
04 Zen 171484 15 minutes ago
03 Ken 468488 20 minutes ago
02 Jon 978284 7 minutes ago
04 Zen 171484 17 minutes ago
02 Jon 978284 32 minutes ago
UPDATE 4: Prefer a very simple solution such as a complex yet clean sql query etc. UPDATE 5: Despite having to give the bounty away, this question still has not been answered with an simple solution to do what I desire.
SELECT t.id, t.time,
(
SELECT count(*)
FROM tab u
WHERE u.id = t.id AND u.time < t.time
ORDER BY u.time
) counter
FROM tab t
ORDER BY counter, t.time
I hope I have understood your question correctly.
Output for random data:
id time counter
2 2 0
0 7 0
4 16 0
1 21 0
3 50 0
2 5 1
1 29 1
0 32 1
4 38 1
3 69 1
2 25 2
1 30 2
0 37 2
4 53 2
2 51 3
4 59 3
0 87 3
4 62 4
2 73 4
0 90 4
Don't forget to use indexes.
Try the following:
1. create SELECT statements for both sets (items with ID1 and items with ID2)
2. use ORDER BY within those statements for time/IDx order
3. add a column
(SELECT COUNT(*) FROM table AS tab2 WHERE tab2.item <= tab1.item) AS rownum
Update: this was rather intended for two tables; after looking at the example updates above and trying some things I think it's rather hard to code that in a single SQL (using SQLite)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With