2016-08-01 58 views
0

我的表是(phone_number,bpm,timestamp)。我想獲取每個phone_number的最新10行的phone_number,avg(bpm)。我試過了..mysql查詢從不同的phone_numbers獲得最新N行的平均值

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子句。

+0

'我不能在我的mysql版本中使用IN子句。請詳細說明。 – Strawberry

+0

我正在使用mysql 5.5,並在我的查詢中使用IN子句時出現此錯誤。 –

回答

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; 
+0

這完美地工作。 (@pn = phone_number,1,1) ) )' '和'SELECT @pn' :='',@rn:= 0' 你能解釋一下嗎? –

+1

@HarishVishwakarma。 。 。在MySQL文檔中查找用戶變量。這些是實現與ANSI標準'row_number()'函數等效的用戶變量。 –