简体   繁体   中英

Sort the data in alphanumeric order using postgresql

I am using php 5.3 for my code. and i want to sort my data in following format.

Building 01 - 101
Building 01 - 150

Building 02 - 100
Building 02 - 105
Building 03 - 099

public static function fetchSortedPropertyUnits() {
    $strSql = 'SELECT pu.*,pb.building_name
               FROM property_units pu  
                LEFT JOIN property_buildings pb ON( pu.property_building_id = pb.id )  
                WHERE pu.management_company_id = ' . $intManagementCompanyId . '
                    AND pu.property_id = ' . $intPropertyId . '  
               ORDER BY  
                COALESCE ( CAST ( SUBSTRING ( pb.building_name FROM \'([a-zA-Z ]{1,26})\' ) AS VARCHAR ), \'\' ),
                    COALESCE ( CAST ( SUBSTRING ( pb.building_name FROM \'([0-9]{1,10})\' ) AS INTEGER ), 0 ),
                    COALESCE ( CAST ( SUBSTRING ( pu.unit_number FROM \'([a-zA-Z ]{1,26})\' ) AS VARCHAR ), \'\' ),
                    COALESCE ( CAST ( SUBSTRING ( pu.unit_number FROM \'([0-9]{1,10})\' ) AS INTEGER ), 0 ),
                    pb.building_name,
                    pu.unit_number';  
            return self::fetchPropertyUnits( $strSql, $objDatabase );  }

This is the fetch function i used.
& i use it in my code as follows.

$arrobjSortedPropertyUnits  =   CPropertyUnits::fetchSortedPropertyUnits( $this->m_objPropertyUtilitySetting->getManagementCompanyId(), $this->m_objPropertyUtilitySetting->getPropertyId(), $this->m_objClientDatabase );  
foreach( $this->m_arrobjPropertyUnits as $objPropertyUnit ) {  
    $strUnitNumber = $objPropertyUnit->getUnitNumber();  
    if( true == valObj( $objPropertyUnit, 'CPropertyUnit' ) && true == $objPropertyUnit->getPropertyBuildingId() ) {  
        $strUnitNumber = $objPropertyUnit->getBuildingName() . ' - ' . $objPropertyUnit->getUnitNumber();  
        $objPropertyUnit->setUnitNumber( $strUnitNumber );  
    }  
}  

I want to sort it in proper order, if property don't have building then only sort it by unit numbers. Any help is welcome for this issue. Thanks.

In this case you need to look at your strings and see how to process them. it looks like have a string in the form of "Building X - Y" and you want to sort on X then Y. The simple thing to do is to turn this into a numeric array. You can do this by:

 .....
 ORDER BY string_to_array(regexp_replace(building_name, 'Building ', ''), ' - ')::int[]

This will turn "Building X - Y" into {X,Y} so Building 1 - 100 becomes {1,100} and so forth. These will be ordered starting with the left-most element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM