首页 > 解决方案 > 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 的答案都差不多)

标签: sqlsqlitegroup-by

解决方案


您可以使用聚合。许多数据库支持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()


推荐阅读