0
我在新的軌道,如何計算的has_many協會之間的平均在軌的較大值3
我有一個個人資料表和配置文件歷史記錄表。個人資料有許多資料歷史 檔案表有 ID和CURRENT_COUNT列和輪廓史上具有PROFILE_ID,數列
我要計算所有擁有比一般各自輪廓歷史
的計數值的CURRENT_COUNT更大的輪廓我怎麼能在軌道實現這個3.
我在新的軌道,如何計算的has_many協會之間的平均在軌的較大值3
我有一個個人資料表和配置文件歷史記錄表。個人資料有許多資料歷史 檔案表有 ID和CURRENT_COUNT列和輪廓史上具有PROFILE_ID,數列
我要計算所有擁有比一般各自輪廓歷史
的計數值的CURRENT_COUNT更大的輪廓我怎麼能在軌道實現這個3.
相應的SQL查詢
SELECT p.id, MIN(current_count), AVG(ph.count)
FROM profiles p
INNER JOIN profile_histories ph on p.id=ph.profile_id
GROUP BY ph.profile_id, p.id
HAVING MIN(current_count) > AVG(ph.count)
讓構建軌道方式:
Profile.joins(:profile_histories)
.select('profiles.id, MIN(profiles.current_count), AVG(profile_histories.count)')
.group('profile_histories.profile_id, profiles.id')
.having('MIN(profiles.current_count) > AVG(profile_histories.count)')
你嘗試過什麼樣的事情呢? –
@JustinWood我已經試過類似Profile.includes(:profile_histories) \t。選擇 - \t。集團('profile_histories( '曲線*,profile_histories *,(AVG(profile_histories.count)profiles.current_count)。') .profile_id「) – Jhon