merge and order two columns in the same model

隐身守侯 提交于 2019-12-11 02:23:39

问题


If I had an ActiveRecord model, Foo, which had two date columns, date_1 and date_2, and I wanted to sort by the later of the two columns (the date that was later), how would this be done? Answers will be judged based on simplicity of the code and the least sql used.

similar question Ruby or Rails sort on two/multiple date fields

I'm leaning towards the following but I don't know if there is a better way. Tested code:

 Foo.select("CASE 
     WHEN date_1 > date_2 THEN date_1
     ELSE date_2
     END AS later_date, *").order("later_date desc")

回答1:


Try using this:

Foo.order('GREATEST(date_1, date_2) DESC')


来源:https://stackoverflow.com/questions/35206355/merge-and-order-two-columns-in-the-same-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!