A
A
Angelxalfa2015-04-06 11:53:35
PHP
Angelxalfa, 2015-04-06 11:53:35

Sort data from textbox as number?

Hello!
There is a table with fields that contain mixed data (numbers with letters).
When getting data from this table, you need to sort them as numbers.
I used to work in conjunction with MySQL, but now I needed to switch to Postgress
used a query

select data from ".$prefix."$table WHERE pre_data = '$pre_data' ORDER BY (data+0)

In MySQL, such a query passed without problems, but postgres gives an error.
How can you achieve what you want in postgres?
As a result, I decided through sorting in the array using php methods
// Получение списка столбцов
foreach ($out2 as $key => $row) {
$volume[$key] = $row['data'];
}
//Сортировка
array_multisort($volume,SORT_NUMERIC, SORT_ASC, $out2);

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
krypt3r, 2015-04-06
@krypt3r

Extract all the numeric data you want to sort by from the data column into a new numeric type column and sort by it.

H
He11ion, 2015-04-06
@He11ion

SELECT * FROM unnest(array['1','2б','2а','1а','2']) a ORDER BY a ASC;

gives
1
1a
2
2a
2b
on postgres 9.4.1

M
mnbck, 2015-04-07
@mnbck

For oracle, these tricks work - www.techonthenet.com/oracle/questions/sort1.php
For Postgre, I think it should work too.

S
sokollondon, 2019-09-09
@sokollondon

ORDER BY substring(column_name, '^[0-9]+')::int
Or so that after the number the letters are sorted alphabetically

ORDER BY substring(column_name, '^[0-9]+')::int, substring(column_name, '[^0-9]*$')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question