gpt4 book ai didi

mysql - sql 计算两个值共享另一列中相同值的次数

转载 作者:行者123 更新时间:2023-11-29 01:15:54 26 4
gpt4 key购买 nike

这是我的表格:

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

结果如下:

ID1 ID2 N_State
---------
0 1 1
2 3 2
2 0 1

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

最佳答案

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

关于mysql - sql 计算两个值共享另一列中相同值的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com