sql - SQL中有没有办法通过自反属性组合对?
问题描述
假设我有一张桌子(team1,team2,score)。
数据:
A B 40
B A 20
我如何将它们组合在一起,以便我的最终结果是
A B 60
解决方案
正如 Lukasz 所建议的,大多数数据库都支持least()
/ 。greatest()
更通用的解决方案使用case
:
select (case when team1 < team2 then team1 else team2 end) as team1,
(case when team1 < team2 then team2 else team1 end) as team2,
sum(score)
from t
group by (case when team1 < team2 then team1 else team2 end),
(case when team1 < team2 then team2 else team1 end);
如果所有对都在两个方向的数据中,那就没问题了。但是,如果某些对仅在一个方向上,那么您可能会得到原始数据中没有的结果。那是:
team1 team2 score
6 3 10
将转换为:
team1 team2 score
3 6 10
该对不在原始数据中的位置。
如果这是不可取的,您可以使用:
select team1, team2, sum(score)
from ((select team1, team2, score
from t
where team1 <= team2
) union all
(select team2, team1 score
from t
where team2 < team1 and
not exists (select 1 from t t2 where t2.team1 = t.team2 and t2.team2 = t.team1
)
)
) t
group by team1, team2;
推荐阅读
- python - 用介于两者之间的日期填写开始/结束日期列表
- javascript - 更改任何元素的悬停样式而不更改父项的样式
- mongodb - 我什么时候可以在命令行中使用命令“mongod”?
- asp.net-core - 从另一个项目中读取配置 - Log4Net ASP.NET Core 3.1
- php - Gulp 和 browserSync 配置与 MAMP:卡在重新加载浏览器
- shell - 当我使用 -w 而不是没有它时,为什么 grep 会返回匹配项?
- docker - GitLab 管道未执行 docker 映像的脚本部分中的命令
- javascript - 循环遍历函数对象并为对象中的每个函数添加一个新方法
- firebase - 如何从 Firebase 存储中的所有文件中删除下载 URL 选项?
- awk - 打印一个文件的行数和另一个文件的总数