我们有类型enum值的扇区列是['中场','前锋','后卫','守门员']。
想按照日期各个部门的最高分和每个部门组的选手名称输出。
如果数据未在任何日期预设,那么我们想要null或0。
date │ mid_score │ midfielder │ def_score │ defender
2017-12-26 │ 91 │ Dele Alli │ 74 │ Jan Vertonghen
2017-12-27 │ 61 │ Eric Dier │ 68 │ maya yoshida
您想要的聚合查询将由date
和sector
进行分组,然后找到该组的最大分数。我们可以将此查询放入子查询中,然后将表连接到它,条件是日期,扇区和分数与子查询中的日期,扇区和最大分数匹配。
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
SELECT date, sector, MAX(score) AS max_score
FROM yourTable
GROUP BY date, sector
) t2
ON t1.date = t2.date AND
t1.sector = t2.sector AND
t1.score = t2.max_score
ORDER BY
t1.date,
t1.sector;
关于缺失数据,处理该数据的一个选项是使用日历表。我认为,那个会有点太大而无法回答答案,但我会把它作为你的功课。
编辑:如果您希望每个日期有一行,那么我们可以按日期对外部查询执行第二次汇总:
SELECT
t1.date,
GROUP_CONCAT(t1.sector ORDER BY t1.score) sectors,
GROUP_CONCAT(t1.score ORDER BY t1.score) scores
FROM yourTable t1
INNER JOIN
(
SELECT date, sector, MAX(score) AS max_score
FROM yourTable
GROUP BY date, sector
) t2
ON t1.date = t2.date AND
t1.sector = t2.sector AND
t1.score = t2.max_score
GROUP BY
t1.date
ORDER BY
t1.date;