简体   繁体   English

如何根据多个MAX条件在每个组中选择一条记录?

[英]How to select a single record per group based on multiple MAX conditions?

I've got 2 tables: 我有2张桌子:

workouts
id,    name, difficulty_level, rounds_count, some other columns...
 1,     'a',                1,            1
 2,     'a',                1,            5
 3,     'a',                2,            1
 4,     'a',                2,            5

 5,     'b',                1,            1 
 6,     'b',                1,            5
 7,     'b',                2,            1
 8,     'b',                2,            5

trainings
id, user_id,       workout_id,   created_at, some other columns...
 1,       1,                6,   2014-07-06
 2,       1,                1,   2014-07-07
 3,       1,                4,   2014-07-08
 4,       1,                7,   2014-07-09

Here's SQL Fiddle with this data: http://sqlfiddle.com/#!15/1d12d 这是带有此数据的SQL Fiddle: http ://sqlfiddle.com/#!15/1d12d

I'd like to find the "hardest" workout for each workout name that was ever performed by given user. 我想为给定用户执行的每个锻炼名称找到“最难”的锻炼。 By "the hardest" I mean workout that has the highest difficulty level and the highest rounds count for that difficulty level. “最困难的”是指具有最高难度级别和最高回合次数的锻炼。 In the example given above I should get workout records with ids 4 and 7. 在上面给出的示例中,我应该获得ID为4和7的锻炼记录。

There's also another possible way to solve it. 还有另一种可能的方法来解决它。 The whole idea of finding the "hardest" workout per given workout name is to prevent creating new trainings for given user with "easier" workouts than those already performed. 为每个给定的锻炼名称查找“最难”锻炼的整个想法是,防止为给定用户(比已经执行的锻炼更“容易”)创建新的锻炼。 Thus, assuming that it works correctly, the last training for given workout name should always point to the "hardest" workout so far. 因此,假设它正确运行,给定锻炼名称的最后训练应始终指向迄今为止“最困难”的锻炼。

I'm using PostgreSQL 9.3. 我正在使用PostgreSQL 9.3。

SQL Fiddle SQL小提琴

select distinct on (user_id, name)
    user_id, name, w.id as workout_id,
    difficulty_level, rounds_count
from
    workouts w
    inner join
    trainings t on t.workout_id = w.id
order by user_id, name, difficulty_level desc, rounds_count desc

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

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