[英]Active record interface in ruby for group by and having
我有一個表,其中包含列ID和A1。 id a1 1 b2 1 b1 2 b1 1 b3 2 b2
sql中的查詢將是-
select id, count(*) as TOTAL from table where a1 in (b1, b2) group by(id, a1) having count(*) > 1
我必須在記錄界面中編寫此查詢-
Table.select(:id).where(:a1 => 'b1').group(:id, :a1).count.having(count>1)
我收到以下錯誤-
NameError: undefined local variable or method `count' for main:Object
我該如何解決此錯誤。
注意 -我必須在其中包括a1 = b1或a1 = b2,但是由於我在其中也遇到了錯誤,因此將其刪除。
您必須像這樣通過它:
Table.select(:id).where(:a1 => 'b1').group(:id, :a1).having('count(*) > 1')
甚至更好:
Table.select(:id).where(:a1 => 'b1').group(:id, :a1).having('count(*) > ?', 1)
參考: #Having
另一件事,您不能有group(:id, :a1).count.having
原因count
返回哈希,而不是ActiveRecord::Relation
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.