【问题标题】:How to select a single record per group based on multiple MAX conditions?如何根据多个 MAX 条件为每组选择一条记录?
【发布时间】:2014-07-06 15:51:44
【问题描述】:

我有 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

这是处理这些数据的 SQL Fiddle:http://sqlfiddle.com/#!15/1d12d

我想为给定用户执行的每个锻炼名称找到“最难”的锻炼。我所说的“最难”是指具有最高难度级别的锻炼,并且该难度级别的最高回合数。在上面给出的示例中,我应该获得 id 为 4 和 7 的锻炼记录。

还有另一种可能的解决方法。为每个给定锻炼名称找到“最难”锻炼的整个想法是防止为给定用户创建比已经执行的锻炼“更容易”的新培训。因此,假设它正常工作,给定锻炼名称的最后一次训练应该始终指向迄今为止“最难”的锻炼。

我使用的是 PostgreSQL 9.3。

【问题讨论】:

标签: sql postgresql greatest-n-per-group


【解决方案1】:

SQL Fiddle

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-11
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多