SQLite Forum

Get column rank from values in selected row
Login
I think I have this worked out now:

DDL of table:
CREATE TABLE WEIGHT_CENT_M36(MALE INTEGER, MONTHS REAL, WEIGHT REAL, CENTILE INTEGER)

Sample data (up to 2.5 months):

MALE	MONTHS	WEIGHT	CENTILE
---------------------------------
1	0.0	2.36	3
1	0.0	2.53	5
1	0.0	2.77	10
1	0.0	3.15	25
1	0.0	3.53	50
1	0.0	3.88	75
1	0.0	4.17	90
1	0.0	4.34	95
1	0.0	4.45	97
1	0.5	2.80	3
1	0.5	2.96	5
1	0.5	3.21	10
1	0.5	3.60	25
1	0.5	4.00	50
1	0.5	4.39	75
1	0.5	4.72	90
1	0.5	4.91	95
1	0.5	5.03	97
1	1.5	3.61	3
1	1.5	3.77	5
1	1.5	4.02	10
1	1.5	4.43	25
1	1.5	4.88	50
1	1.5	5.33	75
1	1.5	5.73	90
1	1.5	5.97	95
1	1.5	6.12	97
1	2.5	4.34	3
1	2.5	4.50	5
1	2.5	4.75	10
1	2.5	5.18	25
1	2.5	5.67	50
1	2.5	6.18	75
1	2.5	6.64	90
1	2.5	6.92	95
1	2.5	7.11	97
2	0.0	2.41	3
2	0.0	2.55	5
2	0.0	2.75	10
2	0.0	3.06	25
2	0.0	3.40	50
2	0.0	3.72	75
2	0.0	3.99	90
2	0.0	4.15	95
2	0.0	4.25	97
2	0.5	2.76	3
2	0.5	2.89	5
2	0.5	3.10	10
2	0.5	3.44	25
2	0.5	3.80	50
2	0.5	4.15	75
2	0.5	4.45	90
2	0.5	4.63	95
2	0.5	4.74	97
2	1.5	3.40	3
2	1.5	3.55	5
2	1.5	3.77	10
2	1.5	4.14	25
2	1.5	4.54	50
2	1.5	4.95	75
2	1.5	5.31	90
2	1.5	5.52	95
2	1.5	5.66	97
2	2.5	4.00	3
2	2.5	4.15	5
2	2.5	4.39	10
2	2.5	4.78	25
2	2.5	5.23	50
2	2.5	5.68	75
2	2.5	6.09	90
2	2.5	6.33	95
2	2.5	6.49	97

SQL:

select round(max(min(c * (m / ?), 97), 3), 0) as cent from 
(select months as m, weight as w, abs(1 - weight / ?) as p, centile as c from WEIGHT_CENT_M36
where male = 1 and
months > (select max(months) from WEIGHT_CENT_M36 where months < ?)
and 
months <= (select min(months) from WEIGHT_CENT_M36 where months >= ?)
order by p asc limit 1)

where the first place holder is months and the second one weight and the 2 remaining ones months again.
This seems to be working OK in some light testing.

RBS