I´m sorting by Price, look:
SELECT Price
FROM re2_listings
ORDER BY Price asc
Result:
1.200.000,00
1.500.000,00
200,00
3.000,00
...but the correct way is:
200,00
3.000,00
1.200.000,00
1.500.000,00
Understand? How to do this?
-
$q1 = "select Price from re2_listings order by CAST(Price AS Float) asc"; -
Obviously, VARCHAR is not the best datatype for the storage of numerical amounts. If you must use it, you need to CAST the price column to an appropriate numeric type in the SELECT and ORDER BY parts of your statement, or create a view containing the CAST and SELECT from the view.
The datatype to CAST to, and the syntax for CASTing are product-dependent.
-
first, it helps to know your SQL variant to answer your question.
If you still have the ability to control the schema, you are much better off using a numeric data type (e.g. int or float) for the column and formatting it as a price when it is displayed.
-
MySQL or SQL Server supports:
SELECT t.price FROM (SELECT r.price CAST(r.price AS DECIMAL(15,2)) 'dprice' FROM RE2_LISTING r) t ORDER BY t.dpriceI casted the varchar column to the appropriate data type, and used the alias
dpriceso I could reference it for sorting. If you are sorting in ascending fashion, you don't need to specifyASCif you don't want to - it's the default.Larry Lustig : One can also use the positional indicator ORDER BY 1 to order by the first column in the result set.OMG Ponies : Ordering by ordinals isn't recommended because if the column order changes - so does the ordering.
0 comments:
Post a Comment