简体   繁体   中英

Rails Activerecord Relation: using subquery as a table for a SQL join

Can anybody help me figure out how to write the following SQL statement in Rails?

SELECT * FROM shifts a
INNER JOIN (
    SELECT shifts.date, shifts.time, max(shifts.barber_id) as 'barber_id'
    FROM shifts 
    WHERE shifts.date = '2017-09-06' and shifts.is_free = true
    GROUP BY shifts.date, shifts.time
) b 
ON a.date = b.date AND a.time = b.time AND a.barber_id = b.barber_id
WHERE a.`is_free` = true AND a.date = '2017-09-06'

Because where-conditional is the same in subquery and main query I'm using a scope as following:

scope :available, -> { where('shifts.is_free', true).where('shifts.date', '2017-09-06').order(date: :desc, time: :asc) }

I've also created the scope for subquery:

scope :grouped_shifts, -> { select("date, time, max(barber_id) as barber_id").group(:date, :time).available }

but I can't find out how to chain the scope to join method. Can I pass it as argument? Like that:

scope :something, -> { joins(self.grouped_shifts).available }

Or I shouldn't use scopes in this case? Thanks for help in advance!

Piecing together what you have said in your question and in your first comment on your question, I gather you are trying to do this:

There are many barbers, each with many shifts. Each shift has a date and a time, and each barber may be available or not available on any given shift.

You want to find, for each time slot on 2017-09-06 that has at least one available barber, which barber available in that time slot has the largest id (ordered by time slot)

This is how you do it:

Shift.where(date: '2017-09-06').where(is_free: true).order(:time).group(:time).maximum(:barber_id)

You don't need to group by date, since all the shifts selected will be on the same date. If you wanted to extend this over all dates in the table, then it would look like this:

Shift.where(is_free: true).order(:date, :time).group(:date, :time).maximum(:barber_id)

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