骑手和日期的每日平均

daily average by rider and day

我有一个table

id | price | date
1  | 4.45  | 2016-05-16
1  | 8.46  | 2016-05-16
2  | 11.9  | 2016-05-16
3  | 6.76  | 2016-05-16
3  | 13.55 | 2016-05-16
4  | 4.91  | 2016-05-20
1  | 16.77 | 2016-05-20
3  | 16.18 | 2016-05-20
2  | 6.07  | 2016-05-20
4  | 6.25  | 2016-05-20

我想计算每个id和每天的平均价格以及整体

date       | id   | avg_price
2016-05-16 |  1   |   6.45
2016-05-16 |  2   |   12.72
2016-05-16 |  3   |   6.76
2016-05-16 |Total |   9.02
2016-05-20 |  1   |   16.77
2016-05-20 |  2   |   6.07
2016-05-20 |  3   |   16.18
2016-05-20 |  4   |   5.58
2016-05-20 |Total |   10.04
Overall    |Total |   9.53

我有中级 SQL 技能。我知道如何计算车手的平均值,但每天和总体的总数是我不知道该怎么做的事情

您需要按日期和 ID 分组并使用 WITH ROLLUP 修饰符来获取总数:

SELECT COALESCE(date, 'Overall') date, 
       COALESCE(id, 'Total') id, 
       ROUND(AVG(price), 2) avg_price
FROM tablename
GROUP BY date, id
WITH ROLLUP;

或者,对于 MySql 8.0+:

SELECT CASE WHEN GROUPING(date) THEN 'Overall' ELSE date END date, 
       CASE WHEN GROUPING(id) THEN 'Total' ELSE id END id, 
       ROUND(AVG(price), 2) avg_price
FROM tablename
GROUP BY date, id
WITH ROLLUP;

参见demo