sql - ActiveRecord conditional count -
in application, i'm trying sort items views within last 10 days. i'm using impressionist gem, creates model called impression , records every view here.
i've managed piece of code:
@items = item.joins("left join impressions on impressions.impressionable_id = items.id , impressions.impressionable_type = 'item'") .select("count(distinct(ip_address)) counter, impressionable_id, items.title, items.id, items.image") .group('items.id') .order("counter desc") .page(params[:page]) .per_page(9)
this sorts items total unique views. however, want count impressions have been made within last 10 days. led me add where
method such:
time_range = (time.now - 10.days)..time.now @items = item.joins("left join impressions on impressions.impressionable_id = items.id , impressions.impressionable_type = 'item'") .select("count(distinct(ip_address)) counter, impressionable_id, items.title, items.id, items.image") .where('impressions.created_at' => time_range) .group('items.id') .order("counter desc") .page(params[:page]) .per_page(9)
however, excludes items has no views, not want. these should represented 0 view.
any suggestions how fix problem?
i had use case, along modifications make run on heroku's postgres server.
start_date = (time.now - 10.days) end_date = time.now joins("left join impressions on impressions.impressionable_id = items.id , impressions.impressionable_type = 'item'") .select("count(distinct(case when (impressions.created_at between '#{start_date}' , '#{end_date}') ip_address end)) counter, impressionable_id, items.gender, items.title, items.id, items.image") .group('items.id', 'impressions.impressionable_id') .order("counter desc")
Comments
Post a Comment