select user_id, max(perception_score) as max, min(perception_score) as min from temp_user_notes group by user_id as t1;
我正在尝试在rails活动记录中转换此sql查询,但很难创建别名
答案 0 :(得分:2)
只需在select
方法调用中使用SQL别名功能:
TempUserNote.select('user_id, max(perception_score) as max, min(perception_score) as min').group(:user_id)
答案 1 :(得分:2)
您可以使用ActiveRecord的from
方法将表别名为其他名称。
例如,您的部分查询可能是:
TempUserNote.
select("t1.user_id, (t1.max - t1.min) as std_deviation").
from(
TempUserNote.
select("user_id, max(perception_score) as max, min(perception_score) as min").
group(:user_id),
:t1
)