我有一张桌子。
home team | away team | attendance | home or away|
SD | WP | SD OVAL | 4000 | H |
WP | SD | SD OVAL | 4000 | A |
我希望能够生成一个表格来显示
Team | Home Total | Home Average | Away Total | Away Average | Total | Average |
SD | 4000 | 4000 | 0 | 0 | 4000 | 4000 |
WP | 0 | 0 | 4000 | 4000 | 4000 | 4000 |
我已经尝试了连接和联合,虽然UNION给了我最好的结果,虽然结果只返回三列
Team, HomeAttendance, AveHomeAttendance
这是我的查询(我在MYSQL中还是新手)
SELECT Team,
SUM(Attendance) AS HomeAttendance,
ROUND(AVG(Attendance),0) AS AveHomeAttendance
FROM MatchDetails
WHERE Season = 2014
AND HA = 'H'
GROUP BY TEAM
UNION
SELECT Team,
SUM(Attendance) AS AwayAttendance,
ROUND(AVG(Attendance),0) AS AveAwayAttendance
FROM MatchDetails
WHERE Season = 2014
AND HA = 'A'
GROUP BY TEAM
UNION
SELECT Team,
SUM(Attendance) AS TotalAttendance,
ROUND(AVG(Attendance),0) AS AveTotalAttendance
FROM MatchDetails
WHERE Season = 2014
GROUP BY TEAM
答案 0 :(得分:0)
根据您的更新,您可以使用JOIN
代替UNION
:
SELECT total.HomeTeam AS Team,
IFNULL(SUM(home.Attendance),0) AS HomeAttendance,
IFNULL(ROUND(AVG(home.Attendance),0),0) AS AveHomeAttendance,
IFNULL(SUM(away.Attendance),0) AS AwayAttendance,
IFNULL(ROUND(AVG(away.Attendance),0),0) AS AveAwayAttendance,
IFNULL(SUM(total.Attendance),0) AS TotalAttendance,
IFNULL(ROUND(AVG(total.Attendance),0),0) AS AveTotalAttendance
FROM MatchDetails total
LEFT JOIN MatchDetails home
ON home.id = total.id AND home.HA = 'H'
LEFT JOIN MatchDetails away
ON away.id = total.id AND away.HA = 'A'
WHERE total.Season = 2014
GROUP BY total.HomeTeam;