1

我有以下mysql查询:

SELECT mm_strength.strengthId, mm_strength.date, sum(mm_strength_set.weight) AS total, round(sum(mm_strength_set.weight)/count(mm_strength_set.weight),1) AS average, max(mm_strength_set.weight) AS high
FROM mm_strength
INNER JOIN mm_strength_set
ON mm_strength.strengthId = mm_strength_set.strengthId
WHERE mm_strength.exerciseId = '31' AND mm_strength.customerId = '4'
GROUP BY mm_strength.strengthId 
ORDER BY mm_strength.strengthId
DESC
LIMIT 5

结果是:

| strengthID | date       | total | average | high | progress??
| 403        | 2013-06-08 | 32.5  | 10.8    | 12.5 | avg 10.8-prior avg 10 = 0.8
| 357        | 2013-06-04 | 30.0  | 10.0    | 10.0 | avg 10.0-prior avg 8  = 2.0
| 334        | 2013-06-02 | 24.0  | 8.0     | 8.0  | avg 8-0 (no prior)    = 8.0

我已经尝试了所有方法,但似乎找不到创建以下第 6 列的好方法(进度应显示上一行的平均值增加):

| progress |
| 0.8 |
| 2.0 |
| 8.0 |

你们能帮帮我吗?

4

2 回答 2

0

MySQL 中没有lag() over (),但您可以使用变量和子查询来解决此问题:

http://www.onlamp.com/pub/a/mysql/2007/04/12/emulating-analytic-aka-ranking-functions-with-mysql.html?page=2

于 2013-06-12T21:17:12.057 回答
0

更新为了能够按强度ID按降序对其进行排序,您只需使用外部选择

SELECT t.*
 FROM
(
  SELECT strengthID, date, total, high,
          average - @prev_avg progress, 
          @prev_avg := average average           
    FROM
  (
    SELECT s.strengthId, 
           s.date, 
           SUM(ss.weight) total, 
           ROUND(SUM(ss.weight)/COUNT(ss.weight),1) average, 
           MAX(ss.weight) high
      FROM mm_strength s JOIN mm_strength_set ss
        ON s.strengthId = ss.strengthId
     WHERE s.exerciseId = '31' AND s.customerId = '4'
     GROUP BY mm_strength.strengthId 
     ORDER BY mm_strength.strengthId
     LIMIT 5 
  ) q, (SELECT @prev_avg := 0) n
) t
ORDER BY strengthID DESC

样本输出:

| 实力 | 日期 | 总计 | 高 | 进展 | 平均 |
-------------------------------------------------- ------------------------------
| 403 | 2013 年 6 月 8 日 00:00:00+0000 | 32.5 | 12.5 | 0.8 | 10.8 |
| 第357章 2013 年 6 月 4 日 00:00:00+0000 | 30 | 10 | 2 | 10 |
| 第334章 2013 年 6 月 2 日 00:00:00+0000 | 24 | 8 | 8 | 8 |

这是SQLFiddle演示。

于 2013-06-12T21:31:21.773 回答