简体   繁体   English

Active Record 查询 Distinct Group by

[英]Active Record query Distinct Group by

I have a query, where I am trying to find min score of a user in a grade, in a grade, there are users with the same min score我有一个查询,我试图在一个等级中找到用户的最低分数,在一个等级中,有具有相同最低分数的用户

Example: User A has a score of 2 and user B has a score of 2, so my expectation is to get both the users grouped by grade.示例:用户 A 的得分为 2,用户 B 的得分为 2,因此我的期望是让这两个用户都按等级分组。

However, I am only getting one user.但是,我只有一个用户。 The query is:查询是:

users = Users.all
@user_score = users
      .where.not(score: [ nil, 0 ])
      .select('DISTINCT ON ("users"."grade") grade, "users".*')
      .order('"users"."grade" ASC, "users"."score" ASC')
      .group_by(&:grade)

Please if some can guide me what am i doing wrong here.请如果有人可以指导我我在这里做错了什么。

DISTINCT will cut off all non uniq values in the result, so there is no way to get multiple users with same min score in your query. DISTINCT将切断结果中的所有非 uniq 值,因此无法在您的查询中获得具有相同最小分数的多个用户。

I think you can achieve the desired result with window function:我认为你可以用 window function 达到预期的结果:

SELECT * FROM
 (SELECT *, rank() OVER (PARTITION BY grade ORDER BY score) AS places 
  FROM users
  WHERE score IS NOT NULL AND score != 0
 ) AS ranked_by_score
WHERE places = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM