我们有类型枚举值的扇区列是['中场','前进','后卫'守门员']。
想按照日期各个部门的最高分和每个部门组的选手名称输出。
如果数据未在任何日期预设,那么我们想要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
答案 0 :(得分:2)
您想要的聚合查询将按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;