Rails Postgres query, selecting only items that appear in all search params with associations

前端 未结 1 1028
谎友^
谎友^ 2021-01-13 16:03

I\'m looking to create a Postgres query based on a few user select params.

A user will select a shop and a start and end year. Once submitted I\'m would only like t

相关标签:
1条回答
  • 2021-01-13 16:39

    You could check for what items there is a record for every year. You can do that by checking if the number of distinct years for every item is equal to the total of years (using COUNT DISTINCT):

     number_years = params[:end_year].to_i - params[:start_year].to_i + 1
     @sale_averages = Sale.joins(:shops, :items)
                          .select('items.name, AVG(sale.price) as price')
                          .where("EXTRACT(year from season_year) BETWEEN #{params[:start_year]} AND #{params[:end_year]}")
                          .where('shops.name': params[:select_shop])
                          .group('items.name')
                          .having("(COUNT(DISTINCT(EXTRACT(year from season_year))) = #{number_years})")
    

    I have also used BETWEEN instead of < and >. I think you want to group by item name instead of shop (as it was in you original query).

    0 讨论(0)
提交回复
热议问题