【问题标题】:SQL group by two columns where order doesn't matterSQL 按两列分组,顺序无关紧要
【发布时间】:2020-01-14 12:08:32
【问题描述】:

假设我有这张桌子:

col1|col2|score
x   |y   |1
y   |x   |2
z   |w   |4
w   |z   |2

我想按 col1 和 col2 进行分组,使值来自 col1 或 col2 无关紧要,因此 x|y 和 y|x 组合在一起。聚合函数可以是例如平均。所以我想得到结果:

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 的答案都差不多)

【问题讨论】:

    标签: sql sqlite group-by


    【解决方案1】:

    您可以使用聚合。许多数据库都支持least()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()max() 作为 least()greatest() 的等效项。

    【讨论】:

    • 谢谢!在 SQLite3 中使用 min() 和 max() 并且效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2018-05-19
    • 2011-12-11
    相关资源
    最近更新 更多