簡體   English   中英

紅寶石中的活動記錄界面,用於分組並具有

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM