简体   繁体   中英

How to write SQL query as named_scope?

How can I translate the following SQL query into a named_scope?

select users.*, sum(total_quantity * total_price) as points_spent 
from orders 
join users on users.id = orders.user_id 
where pay_type = 'points' 
group by user_id 
order by points_spent desc

Thanks!

Try This

class User < ActiveRecord::Base

    named_scope :your_name, 
                :select=>" users.*,sum(total_quantity * total_price) as points_spent",       
                :joins => :orders, 
                :conditions => ['pay_type = ?', 'points'], 
                :group ="user_id ", 
                :order=>'points_spent desc'

end

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