2017-07-01 80 views
1

我有以下SQL表:选择N个条目每月价值

Id DateTime    Speed 
1  2017-03-02 19:06:20 50 
1  2017-03-02 19:10:18 52 
1  2017-04-01 20:01:10 55 
2  2017-03-02 18:06:20 60 
2  2017-05-03 19:08:00 61 
3  2017-04-12 19:01:40 80 
3  2017-05-11 19:05:50 82 
3  2017-05-14 11:00:00 81 

我想选择每月任何2项,以便月345将有2个观察值。

任何人都可以帮助如何做到这一点?

预期的结果:

Id DateTime    Speed 
1  2017-03-02 19:06:20 50 
1  2017-03-02 19:10:18 52 
1  2017-04-01 20:01:10 55 
3  2017-04-12 19:01:40 80 
2  2017-05-03 19:08:00 61 
3  2017-05-11 19:05:50 82 
+0

发布预期结果 – RomanPerekhrest

回答

1

我想在MySQL中最有效的一般方法是使用变量:

select t.* 
from (select t.*, 
      (@rn := if(@ym = date_format(date, '%Y-%m'), @rn + 1, 
         if(@ym := date_format(date, '%Y-%m'), 1, 1) 
         ) 
      ) as rn 
     from t cross join 
      (select @ym := '', @rn := 0) params 
     order by date_format(date, '%Y-%m') 
    ) t 
where rn <= 2; 

这从每个月返回任意两行。您可以添加第二个连接键以获得两个特定值 - 前两个,后两个,最高速度或其他值。