简体   繁体   中英

SQL order_by an expression

Let's say I have a column that contains a float value between 1-100.

I'd like to be able to turn that value into a less precise integer between 1-10 then order the results on this new value.

It may seem odd to want to make the ordering less precise but the SQL statement is ordered by 2 columns and if the first is too precise then the 2nd order column would have no weight.

Essentially I would like to group my first order by into 10 groups and then order each of those groups by another column.

SELECT "sites".* FROM "sites" ORDER BY "sites"."rating" DESC, "sites"."price" ASC LIMIT 24 OFFSET 0

edit: This is a rails app using postgresql

What SQL is that? Use a divide function and, if necessary, round it.

In MySQL look at the DIV command. I don't have the means to test this right now, but it might help point you in the right direction:

SELECT "sites".* FROM "sites" ORDER BY "sites"."rating" DIV 2 DESC, ...

SELECT "sites".* 
FROM "sites" 
ORDER BY FLOOR("sites"."rating"/10) DESC, "sites"."price" ASC 
LIMIT 24 OFFSET 0

Use the round function as follows:

    Select sites.* 
    from sites
    order by round(sites.rating/10, -1) desc, sites.price desc

This will convert a value of 99 to 10.

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