Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mimic a ROW_NUMBER() functionality without using ROW_NUMBER()?

Tags:

sql

sqlite

I've been running into this problem on an exercise and it's driving me crazy that I can't fix it... Basically I'm using SQLLite so I'm limited to using any window functions to get a result and the more painful part is that there is no unique id on the already created schema. See example:

**Name,  DateAdded,  Amount**
John,  2015-10-12, 100.00
John,  2015-10-15, 50.00
Aaron, 2015-09-20, 10.00
Paul,  2014-12-20, 24.00
Paul,  2015-12-23, 32.00

What is the alternative to using ROW_NUMBER() in SQL Lite when you don't have any unique id to go by ? I'd like to partition by the name and order by amount.

Thanks in advance.

like image 561
Claudio Avatar asked Dec 08 '25 05:12

Claudio


1 Answers

This is all kinds of ugly, but with no windowing functions this is the only way I know of to mimic the row_number function:

select
  t.Name, t.DateAdded, t.Amount,
  ( select count (*)
     from MyTable u
     where
       t.Name = u.Name and
       t.DateAdded >= u.DateAdded
  ) as row_number
from MyTable t

Results:

John    2015-10-12  100 1
John    2015-10-15  50  2
Aaron   2015-09-20  10  1
Paul    2014-12-20  24  1
Paul    2014-12-23  32  2
like image 180
Hambone Avatar answered Dec 09 '25 18:12

Hambone



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!