简体   繁体   English

计算 MySQL 中的唯一组合

[英]count unique combinations in MySQL

I want to count number of matches between two teams.我想计算两支球队之间的比赛次数。

select home.home_team, home.away_team, (home_matches_against+away_matches_against) as matches
from
(select home_team, away_team, count(home_team) as home_matches_against
from results
group by home_team, away_team) as home
join
(select away_team, home_team, count(away_team) as away_matches_against
from results
group by away_team, home_team) as away
on home.home_team=away.away_team and home.away_team=away.home_team

output:输出: 在此处输入图像描述

As you can see count of matches between tow teams are duplicated.如您所见,两队之间的比赛次数是重复的。

My desired result is for example:我想要的结果是例如:

home team  away _team  matches
England    Scotland    117
Wales      Scotland    106 

and etc. I dont want count of matches to be duplicated等等。我不想重复匹配的数量

您可以添加WHERE子句:

WHERE home.home_team < home.away_team;

You could use LEAST and GREATEST.您可以使用 LEAST 和 GREATEST。 Something like:就像是:

SELECT t1.* 
FROM ( SELECT LEAST(home_team, away_team) AS home_team,
              GREATEST(home_team, away_team) AS away_team,
              matches
       FROM results
      ) AS t1
 GROUP BY t1.home_team, t1.away_team,t1.matches;

https://www.db-fiddle.com/f/uLPPE1DoKjKYBoSXfKahJN/21 https://www.db-fiddle.com/f/uLPPE1DoKjKYBoSXfKahJN/21

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM