使用SQL查询计算具有相同名称的两个不同列中的重复项

时间:2018-12-02 14:21:28

标签: sql oracle

我有下表:

Team1  Team2  result
---------------------
 a       b      a
 b       c      b
 c       a      a
 b       a      b
 b       c      -
 a       b      a
 b       c      b 

我要计算出现在Team1和Team2列中的团队的重复组合,如下所示:

Team1  Team2   count
--------------------
 a       b      3
 b       c      3
 c       a      1

我尝试了以下查询:

SELECT TEAM1,TEAM2, COUNT(*) AS COUNT
FROM TABLE_NAME
GROUP BY TEAM1, TEAM2

我没有得到想要的输出。我得到了以下内容:

Team1  Team2   Count
---------------------
  c      a       1
  b      a       1
  a      b       2
  b      c       3

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:4)

您可以使用least()greatest()

SELECT LEAST(TEAM1, TEAM2) as TEAM1, GREATEST(TEAM1, TEAM2) as TEAM2, COUNT(*) AS CNT
FROM  TABLE_NAME
GROUP BY LEAST(TEAM1, TEAM2), GREATEST(TEAM1, TEAM2);

答案 1 :(得分:0)

您可以将应用于这些列的ascii函数的乘(作为可交换代数运算)分组使用

 with table_name(Team1,Team2,result) as
 (
     select 'a','b','a'  from dual union all
     select 'b','c','b'  from dual union all
     select 'c','a','a'  from dual union all
     select 'b','a','b'  from dual union all    
     select 'b','c',null from dual union all
     select 'a','b','a'  from dual union all
     select 'b','c','b'  from dual
 )
  select min(team1) as team1,max(team2) as team2,
         count(*) as count
    from table_name
   group by ascii(team1)*ascii(team2)  
   order by team1;

TEAM1 TEAM2 COUNT
  a     b     3
  b     c     3
  c     a     1

Rextester Demo