Ordinamento secondo l'ultima cifra
In questa piccola tip andremo a vedere come ordinare secondo il valore dell'ultima cifra di un campo numerico.
Supponiamo di avere una tabella testb con un campo id u cui valori sono:
1,2,3,6,7,10,11,12,18,20 e volere un ordinamento secondo l'ultima cifra del tipo:
10,20,1,11,2,12,3,6,7,18 ossia secondo l'ultima cifra una possibile soluzione potrebbe essere:
create index testtb_last_digit_idx on testtb(right(id::text,1)) ;
select testtb.* from testtb inner join (VALUES ('1',1), ('2',2), ('3',3), ('4',4),('5',5),('6',6), ('7',6), ('8',8), ('9',9),('0',0) ) as x(id, ordering) ON right(testtb1.id::text,1) = x.id ORDER BY x.ordering,testtb.id
Per provare quanto scritto basta scrivere:
CREATE TABLE testtb (id integer );
insert into testtb (id) select * from generate_series(1,10000);
Create index testtb_last_digit_idx on testtb(right(id::text,1));
select testtb.* from testtb inner join (VALUES ('1',1), ('2',2), ('3',3), ('4',4),('5',5),('6',6), ('7',6), ('8',8), ('9',9),('0',0) ) as x(id, ordering) ON right(testtb1.id::text,1) = x.id ORDER BY x.ordering,testtb.id;
E il gioco è fatto....have fun...