[英]SQL order_by an expression
Let's say I have a column that contains a float value between 1-100. 假设我有一列包含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. 我希望能够将该值转换为介于1到10之间的不太精确的整数,然后对这个新值进行排序。
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. 想要使排序不那么精确似乎有些奇怪,但是SQL语句按2列进行排序,如果第一列过于精确,则2nd order列将没有权重。
Essentially I would like to group my first order by into 10 groups and then order each of those groups by another column. 本质上,我想将我的第一个订单分为10组,然后按另一列对每个组进行排序。
SELECT "sites".* FROM "sites" ORDER BY "sites"."rating" DESC, "sites"."price" ASC LIMIT 24 OFFSET 0
edit: This is a rails app using postgresql 编辑:这是一个使用postgresql的Rails应用程序
What SQL is that? 那是什么SQL? Use a divide function and, if necessary, round it. 使用除法函数,必要时将其取整。
In MySQL look at the DIV command. 在MySQL中,查看DIV命令。 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, ... 选择“站点”。*从“站点”中按“站点”。“评级” 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. 这会将99转换为10。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.