本文介绍了在 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 中分组、计数、拥有和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 03:23