我有一张表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.
上面的查询不起作用。我怎样才能达到预期的效果?
内部自联接和聚合可能是您正在寻找的。
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;