如何从MySQL中的表中的一组行中获取平均值和最后一个数据

时间:2016-10-12 06:55:02

标签: mysql sql database-design group-by average

我有一个名为tbl_remit的表

No.|id|employer|ap_from| ap_to |amount|
1  |1 |    a   |01/2016|01/2016|5.00  |
2  |1 |    a   |02/2016|02/2016|5.00  |
3  |1 |    a   |03/2016|03/2016|2.50  |
4  |2 |    b   |01/2016|01/2016|1.00  |
5  |2 |    b   |02/2016|02/2016|1.00  |
6  |2 |    b   |03/2016|03/2016|1.50  |
7  |2 |    b   |04/2016|04/2016|0.50  |

我需要创建一个视图并获得每个雇主的平均金额。

id|employer|Average_opt1|LastRemit_opt2|
1 |    a   |    4.16    |     2.50     |
2 |    b   |    1.00    |     0.50     |

我使用了这段代码。但失败了。

CREATE OR REPLACE VIEW view_potential_collection AS
SELECT id, Employer, AVG(Amount) as Average_Opt1, Amount as LastRemit_Opt2
FROM tbl_remit
GROUP BY id, Employer

2 个答案:

答案 0 :(得分:1)

SELECT T.ID,T.EMPLOYER,T.AMOUNT, (SELECT AVG(AMOUNT) FROM TBL_REMIT WHERE EMPLOYER = T.EMPLOYER) AVGAMT
FROM    TBL_REMIT T
WHERE   T.ROWID = (SELECT MAX(ROWID) FROM TBL_REMIT WHERE EMPLOYER = T.EMPLOYER)
;

结果

+------+----------+--------+----------+
| ID   | EMPLOYER | AMOUNT | AVGAMT   |
+------+----------+--------+----------+
|    1 | a        |   2.50 | 4.166667 |
|    2 | b        |   0.50 | 1.000000 |
+------+----------+--------+----------+
2 rows in set (0.00 sec)

答案 1 :(得分:0)

加入avg值为amount的结果集,其结果为row_number,基于id,雇主和No columns的降序。

<强>查询

SELECT t1.`id`, t1.`employer`, t1.`Average_opt1`, t2.`amount` FROM
(SELECT `id`, `employer`, AVG(`amount`) as `Average_opt1`
FROM tblEmployee
GROUP BY `id`, `employer`)t1
JOIN 
(SELECT `No`, `id`, `employer`, `ap_from`, `ap_to`, `amount`, 
(CASE `id` WHEN @curA THEN @curRow := @curRow + 1 
ELSE @curRow := 1 AND @curA := `id` END) AS rn 
FROM tblEmployee t, 
(SELECT @curRow := 0, @curA := '') r 
ORDER BY `id`, `No` DESC)t2
ON t1.`id` = t2.`id`
AND t2.rn = 1;