sql count两个值从另一列共享相同值的次数

时间:2016-12-19 10:04:35

标签: mysql sql

这是我的表:

SomeViewModel

以下是结果:

ID  State
---------
0   A   
1   A   
2   C   
3   C   
2   A      
3   A    
2   D      
0   D    
2   E      
3   F    

问题是: 计算两个ID共有的状态数并以上述格式输出?

1 个答案:

答案 0 :(得分:7)

select      t1.id,t2.id,count(*) as N_State

from                mytable t1
            join    mytable t2
            on      t2.State = t1.State
                and t2.id > t1.id 

group by    t1.id,t2.id
+----+----+----------+
| id | id | count(*) |
+----+----+----------+
| 0  | 1  | 1        |
+----+----+----------+
| 0  | 2  | 2        |
+----+----+----------+
| 0  | 3  | 1        |
+----+----+----------+
| 1  | 2  | 1        |
+----+----+----------+
| 1  | 3  | 1        |
+----+----+----------+
| 2  | 3  | 2        |
+----+----+----------+

添加行号

select      @i:=@i+1 as i
           ,id1,id2,N_State

from        (select      t1.id as id1,t2.id as id2,count(*) as N_State

             from                mytable t1

                         join    mytable t2

                         on      t2.State = t1.State
                             and t2.id > t1.id 

             group by    t1.id,t2.id
             ) t

             cross join (select @i:=-1) x

order by    id1,id2