问题
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