前提・実現したいこと
railsで同じ曜日、レベルの中での最大値段のものだけをソートするコードを
書いていて、 SQLiteではうまく絞り込みが出来るのですがPostgresだとエラーが出てしまいます。
Postgresで絞り込みをするにはどうしたら良いでしょうか
発生している問題・エラーメッセージ
groopにtitle、priceを入れてしまうと、全部出力されてしまうので避けたいです。
postgres側
Post.group(:level, :day).select('title, day, level, price, max(price) as max_price') Post Load (11.4ms) SELECT title, day, level, price, max(price) as max_price FROM "posts" GROUP BY "posts"."level", "posts"."day" LIMIT $1 [["LIMIT", 11]] Traceback (most recent call last): ActiveRecord::StatementInvalid (PG::GroupingError: ERROR: column "posts.title" must appear in the GROUP BY clause or be used in an aggregate function) LINE 1: SELECT title, day, level, price, max(price) as max_price FR...
該当のソースコード
Post.group(:level, :day).select('title, day, level, price, max(price) as max_price')
SQLlite側
irb(main)>Post.group(:level, :day).select('title, day, level, price, max(price) as max_price') Post Load (2.5ms) SELECT title, day, level, price, max(price) as max_price FROM "posts" GROUP BY "posts"."level", "posts"."day" LIMIT ? [["LIMIT", 11]] => #<ActiveRecord::Relation [#<Post id: nil, title: "test3", day: "月", level: "1", price: "2000">, #<Post id: nil, title: "test2", day: "火", level: "1", price: "1600">, #<Post id: nil, title: "test4", day: "火", level: "2", price: "1800">]>
schema.rb
create_table "posts", force: :cascade do |t| t.string "title" t.string "day" t.string "level" t.string "price" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。