在 Rails 中分组、计数、拥有和排序
Group, count, having, and order by in Rails
我有一个表:people
,其中有一列名为:age
.
我如何计算每个年龄段的人数,从大到小排序,并按至少有 2 人的年龄过滤?
我将如何用原始 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
的计数,但我不知道如何按年龄降序排列,或者添加 having
子句。
试试这样的东西:
Person.select("id, age").group(:id, :age).having("count(id) > 1").order("age desc")
Person.select('COUNT(1) as people_count').order('age DESC').group(:age).having('people_count > 1')
我发现其他答案不适合我。我不得不做这样的事情
Person.group(:age).having('count(*) > 1').order('age desc').count
我有一个表:people
,其中有一列名为:age
.
我如何计算每个年龄段的人数,从大到小排序,并按至少有 2 人的年龄过滤?
我将如何用原始 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
的计数,但我不知道如何按年龄降序排列,或者添加 having
子句。
试试这样的东西:
Person.select("id, age").group(:id, :age).having("count(id) > 1").order("age desc")
Person.select('COUNT(1) as people_count').order('age DESC').group(:age).having('people_count > 1')
我发现其他答案不适合我。我不得不做这样的事情
Person.group(:age).having('count(*) > 1').order('age desc').count