2016-11-28 4 views
0

각 고객의 마지막 날의 마지막 레코드를 통계 테이블에서 가져 오려고합니다. 마지막 날부터 가장 많이 팔린 품목을 가진 고객을 선택하고 싶습니다.모든 고객에게서 레일의 마지막 레코드를 선택하십시오

통계는 매시간 생성되므로 고객의 통계가 여러 개 있지만 마지막으로 통계가 필요합니다.

몇 가지 명령을 시도했지만 오류가 발생했습니다.

Statistic.where("created_at < ?",1.day.ago).select(:customer_id).distinct.order(created_at: :desc) 

또는

Statistic.where("created_at < ?",1.day.ago).select(:customer_id).distinct.last 

가 뽑은와 최고의 솔루션인가? 아니면 2 개의 선택을 만들어야합니까? 어디에서 'sold_items'를 배치해야하는지 잘 모르겠습니다.

해결 방법이 될 수도 있지만 확실하지 않습니다.

Customer.all.each do |customer| 
    stats = customer.statistics.where("created_at < ?",Date.today).last 
    count = stats.sold_items if stats.sold_items > count 
    best = customer if count = stats.sold_items 
end 

모델 : 고객 has_many : 통계 - belongs_to 통계 :

+0

모델 선언을 추가 할 수 있습니까? 첫 번째 쿼리를 작동 시키려면 조인을해야합니다. 그래서 두 번째. – marmeladze

+0

'Customer' 모델과'Statistic' 모델 사이에'has_many''belongs_to' 관계가 있습니까? – sa77

+0

오른쪽. 고객 has_many : 통계 및 통계 belongs_to : 고객 –

답변

1
Statistic.joins("inner join (select customer_id,max(created_at) as created_at from statistics group by customer_id) as stats2 on statistics.customer_id = stats2.customer_id and statistics.created_at = stats2.created_at").pluck("max(statistics.sold_items)") 

이 당신에게 지금까지 마지막 날에 대부분의 항목을 판매 고객으로부터 최대 판매 품목을 줄 것이다 고객,

기본적으로 먼저 각 고객에 대한 마지막 통계가 필요합니다. 해당 통계에서 maximum 개의 sold_items가 필요합니다.

그래서 중첩 된 쿼리 (select customer_id,max(created_at) as created_at from statistics group by customer_id)는 외부 쿼리는 이러한 결과 실제 statistics에 가입하고 그 가을 마지막 날짜 기준 하에서 만을 선택하고, 각 고객에 대한 최대 created_at을 선택하는 것입니다. 끝에 pluck("max(statistics.sold_items)") 그 결과에서 최대 sold_items를 선택하십시오.

HERE은 각 그룹에서 최신 레코드를 찾는 또 다른 링크입니다.

+0

와우, 이거 멋지 네요! 고맙습니다! –