我的表是(phone_number,bpm,timestamp)。我想得到每个电话号码最近10行的电话号码,平均值(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子句。
这是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;