php / mysql-根据比赛结果计算(目标)

时间:2018-09-25 12:17:03

标签: mysql sql group-by sum

我有一个数据库,其中包含一个赛季的所有足球比赛,我想对结果进行一些简单的计算。这是桌子的样子:

+----------+----------+---------------+---------------+--+
| HomeTeam | AwayTeam | HomeTeamGoals | AwayTeamGoals |  |
+----------+----------+---------------+---------------+--+
| team1    | team2    |             3 |             1 |  |
| team3    | team4    |             1 |             2 |  |
| team1    | team3    |             4 |             4 |  |
| team4    | team2    |             0 |             1 |  |
+----------+----------+---------------+---------------+--+

现在我想为每个团队计算4件事:
-主场比赛进球总数
-客场比赛的总进球数
-主场比赛的总进球数
-客场比赛的总进球

通过此查询,我可以正确返回所有有关家庭游戏的信息:

SELECT HomeTeam, SUM(HomeTeamGoals) as HomeTeamGoals, SUM(AwayTeamGoals) as AwayTeamGoals
FROM games
GROUP BY HomeTeam

但是我现在如何(通过相同的查询)获取客场比赛的信息?

结果应如下表所示:

+-------+----------+--------------+----------+--------------+
| team  | home for | home against | away for | away against |
+-------+----------+--------------+----------+--------------+
| team1 |        7 |            5 |        0 |            0 |
| team2 |        0 |            0 |        2 |            3 |
| team3 |        1 |            2 |        4 |            4 |
| team4 |        0 |            1 |        2 |            1 |
+-------+----------+--------------+----------+--------------+

2 个答案:

答案 0 :(得分:1)

尝试使用union all:

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1a1bbfadd62ed68808605a9e7767870d

select hometeam, sum(HomeTeamGoals) as homefor,sum(AwayTeamGoals) as homeagainst, 0 as awayfor, 0 as awayagainst from tablename
group by hometeam

union all

select AwayTeam, 0,0, sum(HomeTeamGoals) as awayfor, sum(AwayTeamGoals) as awayagainst from tablename
group by AwayTeam

输出:

hometeam    homefor homeagainst awayfor awayagainst
team1       7       5            0      0
team4       0       1            0      0
team2       0       0            3      2
team3       0       0            4      4

答案 1 :(得分:0)

您可以尝试

输入:

<div class="fb-share-button"><a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u&amp;src=sdkpreparse" class="fb-xfbml-parse-ignore">Share</a></div>

enter image description here

输出:

create table goals(
homeTeam varchar(10),
awayTeam varchar(10),
homeTeamGoals tinyint,
awayTeamGoals tinyint
);
insert into goals values('team1','team2',3,1),('team3','team4',1,2),('team1','team3',4,4),('team4','team2',0,1);

enter image description here