sql - 根据两个名称列对两个列值求和
问题描述
我是 Postgres 数据库的新手。我有 4 列 homeTeamName、homeTeamGoals、awayTeamGoals、awayTeamName。我想找出每支球队的总进球数(homeTeamGoals + awayTeamGoals)。
select distinct hometeamname, SUM(hometeamgoals + awayteamgoals) as goals
from worldcupsmatches
where worldcupsmatches is not null
group by hometeamname
order by goals desc
数据库如下
我认为我的解决方案是错误的。所以寻找更好的方法
解决方案
您可以如下分隔表格内容,然后应用 SUM 函数:
select teamname, sum(goals) goals
from (
select hometeamname as teamname, hometeamgoals as goals
from worldcupsmatches
where worldcupsmatches is not null
union all
select awayteamname, awayteamgoals
from worldcupsmatches
where worldcupsmatches is not null
) t
group by teamname
order by goals desc, teamname asc
;
推荐阅读
- html - 如何在 angular + ngrx 购物应用程序中将添加到购物车按钮更改为购物车按钮中的视图 ..?
- c - AC 程序在达到一定大小后无法将输出生成到日志文件中
- javascript - 检索 postMessage 事件的完整原始 URL
- c++ - c++中线程是如何实现的
- python - 如何检测图像中黑色区域的百分比并相应地排除图像?
- ios - AVAudioSession 采样率和 AVAudioEngine 输入节点采样率有什么区别?
- devise - 如何规避 Rails 5 设计用户登录身份验证并重定向到页面
- azure-functions - 如何在 Azure 功能应用程序设置中使用存储帐户中的 SAS 连接字符串
- angular - 如何使用 JSON 服务器将数据检索到 Angular 9 中的字段中?
- python-3.x - 如何在不提供路径的情况下保存文件?