引用相似值的sqlite对列

时间:2018-09-10 02:00:34

标签: sql sqlite

我有一个表my_table

sport            score
football         22
basketball       17
baseball         17
baseball         29
hockey           22

我想配对运动中得分相同的列

所需的输出应为

sport1      sport2        times_paired
football    hockey        1
basketball  baseball      1

到目前为止,我的查询中已有

select m1.sport as sport1, m1.score as times_paired, m2.sport as sport2 from mytable m1 where(select count(*) as times_paired, m2.sport  from mytable2 m2 where m1.score = m2.score.

上面的此查询不起作用。我怎样才能达到预期的效果?

1 个答案:

答案 0 :(得分:3)

内部自连接和聚合可能是您想要的。

SELECT t1.sport sport1,
       t2.sport sport2,
       count(*) times_paired
       FROM my_table t1
            INNER JOIN my_table t2
                       ON t2.score = t1.score
                          AND t2.sport > t1.sport
       GROUP BY t1.sport,
                t2.sport;