mysql查询从不同的phone_numbers

时间:2016-08-01 20:23:47

标签: mysql sql group-by having

我的表是(phone_number,bpm,timestamp)。我想为每个phone_number获取最近10行的phone_number,avg(bpm)。我试过..

SELECT phone_number, AVG( bpm ) 
FROM (
SELECT * 
FROM table_name
WHERE bpm !=0
ORDER BY timestamp DESC
) AS temp
GROUP BY phone_number
HAVING COUNT( * ) <=10

此查询提供空结果。我不能在我的mysql版本中使用IN子句。

1 个答案:

答案 0 :(得分:2)

这是MySQL的痛苦。最合理的解决方案是使用变量来枚举行然后聚合:

SELECT phone_number, AVG(bpm)
FROM (SELECT t.*,
             (@rn := if(@pn = phone_number, @rn + 1,
                        if(@pn := phone_number, 1, 1)
                       )
             ) as rn
      FROM table_name t CROSS JOIN
            (SELECT @pn := '', @rn := 0) params
      WHERE bpm <> 0
      ORDER BY phone_number, timestamp DESC
     ) t
WHERE rn <= 10
GROUP BY phone_number;