在 Rails 中分组、计数、拥有和排序

编程入门 行业动态 更新时间:2024-10-15 12:38:30
本文介绍了在 Rails 中分组、计数、拥有和排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个表:people,其中有一列名为:age.

I have a table: people with a column named: age.

如何计算每个年龄的人数,从大到小排序,按年龄过滤,其中至少有 2 个人?

How can I get a count of the people with each age, ordered from oldest to youngest, filtered by ages with at least 2 people in it?

我将如何用原始 SQL 编写它:

SELECT COUNT(1) AS people_count, age FROM people GROUP BY age HAVING people_count > 1 ORDER BY age DESC

在 Rails 中(我不知道怎么做):

Person.group(:age).count 将按 age 获取计数,但我不知道如何按年龄降序排列,或者添加have 子句.

Person.group(:age).count will get me the counts by age, but I can't figure out how to order it descendingly by age, or add the having clause.

推荐答案

尝试类似:

Person.select("id, age").group(:id, :age).having("count(id) > 1").order("age desc")

更多推荐

在 Rails 中分组、计数、拥有和排序

本文发布于:2023-11-22 03:44:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615846.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!