【问题标题】:SQL group by two columns where order doesn't matter, keep other columnsSQL按顺序无关紧要的两列分组,保留其他列
【发布时间】:2020-01-14 19:47:23
【问题描述】:

假设我有这张桌子 - t1:

col1|col2|col3|score
x   |y   |a   |1
y   |x   |b   |2
z   |w   |c   |4
w   |z   |d   |2

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

col1|col2|col3|score
x   |y   |a   |1.5
y   |x   |b   |1.5
z   |w   |c   |3
w   |z   |d   |3

我可以这样做:

create table t2 as select min(col1,col2) as col1, max(col1,col2) as col2 , avg(score) as score from t1 group by min(col1, col2), max(col1, col2);
select * from t1 inner join t2 on (t1.col1 = t2.col1 and t1.col2 = t2.col2) or (t1.col1 = t2.col2 and t1.col2 = t2.col1);

但是:
一种。我不确定它是否正确并且
湾。使用 SQLite 处理真实数据(30 万行的表)需要很长时间。
有没有更简单/更快的方法?

谢谢!

【问题讨论】:

    标签: sqlite group-by


    【解决方案1】:

    试试AVG()窗口函数:

    select col1, col2, col3,
      avg(score) over (partition by min(col1, col2), max(col1, col2)) score
    from t1 
    order by col3 
    

    请参阅demo
    结果:

    | col1 | col2 | col3 | score |
    | ---- | ---- | ---- | ----- |
    | x    | y    | a    | 1.5   |
    | y    | x    | b    | 1.5   |
    | z    | w    | c    | 3     |
    | w    | z    | d    | 3     |
    

    【讨论】:

    • 这是一种非常优雅的方式,可以在顺序无关紧要的情况下合并两列。
    【解决方案2】:

    使用MIN/MAX 技巧:

    SELECT
        t1.col1,
        t1.col2,
        t1.col3,
        t2.score
    FROM yourTable t1
    INNER JOIN
    (
        SELECT MIN(col1, col2) AS col1, MAX(col1, col2) AS col2, AVG(score) AS score
        FROM yourTable
        GROUP BY MIN(col1, col2) AS col1, MAX(col1, col2)
    ) t2
        ON MIN(t1.col1, t1.col2) = t2.col1 AND
           MAX(t1.col1, t1.col2) = t2.col2;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      相关资源
      最近更新 更多