mysql 查询不同 phone_numbers 的最新 N 行的平均值
mysql query to get the average from the latest N rows for distinct phone_numbers
我的 table 是(phone_number,bpm,时间戳)。我想获取每个 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 子句
这是 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;
我的 table 是(phone_number,bpm,时间戳)。我想获取每个 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 子句这是 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;