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
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).