如何按列中的特定格式订购?

时间:2016-12-16 10:57:42

标签: mysql sql database bash

我有一个包含如下数据的列:

{Population: 1331415}
{Population: 44234}
{Population: 214124212}
{Population: 222222}

我需要在{Population:之后的数字,以及另一个名为Name的列(它包含城市的名称)中按数字排序数据库

3 个答案:

答案 0 :(得分:1)

使用GNU sort-n进行数字排序,-k标记基于2nd字段进行排序。

sort -n -k2 file
{Population: 44234}
{Population: 222222}
{Population: 1331415}
{Population: 214124212}

答案 1 :(得分:1)

一种方法是使用长度和值:

order by length(col) desc, col desc

另一种方法是提取数值并将其转换为数字:

order by substring_index(col, ': ', -1) + 0 desc

答案 2 :(得分:0)

检查这个。

            ORDER BY 
            CONVERT( (REPLACE (substring_index(ColumnName, ': ',-1),'}','')), 
            UNSIGNED  INTEGER ) DESC

示例:

        SELECT * ,
        CONVERT((REPLACE(substring_index(A, ': ',-1),'}','')),UNSIGNED  INTEGER )'ORDER'
        FROM (
            SELECT '{Population: 1331415}' AS A UNION
            SELECT '{Population: 44234}' UNION
            SELECT '{Population: 214124212}' UNION
            SELECT '{Population: 222222}'
            )B 
        ORDER BY 
        CONVERT( (REPLACE (substring_index(A, ': ',-1),'}','')), UNSIGNED  INTEGER )
        DESC
  

输出:

enter image description here