sql - SQL 按两列分组,顺序无关紧要
问题描述
假设我有这张桌子:
col1|col2|score
x |y |1
y |x |2
z |w |4
w |z |2
我想按 col1 和 col2 进行分组,使值来自 col1 或 col2 无关紧要,因此 x|y 和 y|x 组合在一起。聚合函数可以是例如AVG。所以我想得到结果:
col1|col2|score
x |y |1.5
z |w |3
或者
col1|col2|score
x |y |1.5
y |x |1.5
z |w |3
w |z |3
我知道我可以按两列分组,但这对我没有帮助,那我该怎么做呢?(我使用的是 SQLite3,但我猜任何 SQL DB 的答案都差不多)
解决方案
您可以使用聚合。许多数据库支持least()
and greatest()
,这将这个逻辑简化为:
select least(col1, col2) as col1, greatest(col1, col2) as col2, avg(score) as score
from t
group by least(col1, col2), greatest(col1, col2)
order by least(col1, col2), greatest(col1, col2);
在不支持这些函数的数据库中,您可以使用case
表达式:
least(co1, col2)
-->(case when col1 < col2 then col1 else col2 end)
greatest(co1, col2)
-->(case when col1 < col2 then col2 else col1 end)
在 SQLite 中,您可以将min()
andmax()
与多个参数一起用作 and 的等价least()
物greatest()
。
推荐阅读
- vim - vim 中没有可用的有向图
- gitlab - 图像未在 Gitlab 中以 md 格式文件呈现
- python - 需要在 Dataframe 中将对象列转换为 int/float 以便稍后可以对其进行一些操作
- wpf - 如何实现在 WPF 树视图中选择树节点的命令
- docker - Flask、NGINX、uWSGI认证后随机重定向问题
- c# - 按 CTRL + S 时,Visual Studio 会自动创建异常文件
- python - 在 python 的子类构造函数中将对象作为列表传递
- java - 逻辑问题:列表响应的 REST-API 缓存
- reactjs - 如何在nextjs中获取上一页url
- upgrade - 如何以零停机时间将 istio 1.4.3 升级到最新版本