在使用GROUP BY WEEK时,MySQL通过SQL中的另一列按max(列)选择行?

时间:2015-06-17 19:26:57

标签: mysql

对于每周,我想为每个不同的代表值选择权重最高的行

-------------------------------------
| id | reps | weight |     date     |
| 1  |  1   |  15    |   2015-06-10 |
| 2  |  2   |  29    |   2015-06-12 |
| 3  |  1   |  30    |   2015-06-13 |
| 4  |  4   |  11    |   2015-06-14 |
| 5  |  1   |  15    |   2015-06-29 |
| 6  |  1   |  9     |   2015-06-30 |

我希望它返回

-------------------------------------
| id | reps | weight |     date     |
| 2  |  2   |  29    |   2015-06-12 |
| 3  |  1   |  30    |   2015-06-13 |
| 4  |  4   |  11    |   2015-06-14 |
| 5  |  1   |  15    |   2015-06-29 |

我试过

SELECT MAX(weight) as weight, reps, date, id FROM log_items
GROUP BY reps, WEEK(date)

但它似乎返回完全随机的结果,我也尝试使用子查询,但它们也没有工作(我猜我做错了)

1 个答案:

答案 0 :(得分:0)

尝试:

SELECT * 
FROM log_items
WHERE (reps, WEEK(date), weight ) in (
      SELECT reps, WEEK(date) , MAX(weight)
      FROM log_items
      GROUP BY reps, WEEK(date)
 )

演示:http://sqlfiddle.com/#!9/4bf84/9