Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何在Rails中按计数分组和排序?_Sql_Ruby On Rails_Ruby_Ruby On Rails 4_Rails Activerecord - Fatal编程技术网

Sql 如何在Rails中按计数分组和排序?

Sql 如何在Rails中按计数分组和排序?,sql,ruby-on-rails,ruby,ruby-on-rails-4,rails-activerecord,Sql,Ruby On Rails,Ruby,Ruby On Rails 4,Rails Activerecord,如何将SQL转换成Ruby/Rails select tag, count(*) c from tags group by tag order by c desc; 我发现我可以做到: Post.select(:user_id).group(:user_id).count Post.count(group: :user_id) Post.all(group: :user_id, select: "user_id, count(*) as count") Post.find(:all, sele

如何将SQL转换成Ruby/Rails

select tag, count(*) c from tags group by tag order by c desc;
我发现我可以做到:

Post.select(:user_id).group(:user_id).count
Post.count(group: :user_id)
Post.all(group: :user_id, select: "user_id, count(*) as count")
Post.find(:all, select: "user_id, count(*) as count", group: :user_id)
#1返回一个散列#2、#3和#4发出了反对警告。(我正在使用Post,因为我还没有标签的任何数据。)

试试:

 Tag.select("tag, count(*) as total_count").group("tag").reverse_order

有关更多信息,请阅读:

我必须调整它:
标记。选择(“标记,计数(*)作为总计数”)。组(“标记”)。顺序(“总计数”)。反转顺序
反转顺序不接受参数。我以:
self.tags.select(:tag,“count(*)as count”).group(:tag.order(count::desc.map{t | t.tag}.join(“”)
结束。谢谢这仍然不起作用:
ERROR:column“tags.id”必须出现在groupby…
我想如果您不指定要排序的列,它默认为
id
列,而该列不在
选择中。