Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite SELECT that returns ids and positions

Tags:

sql

sqlite

Using a SQLite SELECT statement, I'd like to be able to get the position of each results.

Is that even possible?

Table:

fk_id   idx
0       0
0       1
0       2
1       0
1       1
1       3
1       4
2       0

Having [fk_id, idx] being unique.

Query:

SELECT `idx`, <??> from `mytable` WHERE `fk_id`=1

Results:

idx   <??>
0     0
1     1
3     2
4     3

The <??> being the "order"/"position"/"index" information I seek.

like image 808
Arnaud Leymet Avatar asked Feb 03 '26 14:02

Arnaud Leymet


1 Answers

SQLite doesn't have analytic support - the closest you can get is to use a subselect:

SELECT mt.idx,
       (SELECT COUNT(*) - 1
          FROM mytable t
         WHERE t.fk_id = mt.fk_id
           AND t.idx <= mt.idx) AS position
  FROM mytable mt
 WHERE mt.fk_id = 1

The caveat here is that if you have duplicate idx values, they all get the same position value. The only way with this method to get distinct values, is to add criteria that for logic to distinguish which of the duplicates comes first.

like image 126
OMG Ponies Avatar answered Feb 05 '26 04:02

OMG Ponies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!