一列基于另一列的多个组合



我有一个这样的表(我的所有id2都不同(:

id1     id2
---     ---
A       1
A       2
B       3
C       4

并且我想要为id1的每个不同项生成id2的组合的列表。

在这种情况下,我会有:((1,3,4(,(2,3,4((

当然,id1不限于3个项目,它可以是更少/更多,我希望SQL查询或Python脚本能够在id1中的不同项目数量下工作

示例:

id1     id2
---     ---
A       1
A       2
B       3
B       4
C       5
D       6

将产生:((1,3,5,6(,(1,4,5,6

等等

MySQL脚本(即在加载到Python之前(或Python代码片段(一旦加载了原始表(都可以。

我为自己感到骄傲(哈哈(我发现了一些不错的东西

"compte"是来自my_table 的SELECT COUNT(DISTINCT id1(

"组合"是我所有的组合(例如[(A,1(,(A,2(,(B,3(,(B,4(,(C,5(,(D,6(]

# i generate my own list comprehension
for k in range(compte):
toto = 'a'+str(k)+'[1]' + ( ',' if k != 0 else '' ) + toto
titi = 'for a'+str(k)+' in combis ' + titi
tutu = 'a'+str(k)+'[0]' + ( '>' if k != 0 else '' ) + tutu
exec('print([['+toto+'] '+titi+'if '+tutu+'])')

我假设id数据的形式如下:

combis = [('A', 1), ('A', 2), ('B', 3), ('B', 4), ('C', 5), ('D', 6)]

然后

from collections import defaultdict
from itertools import product
groups = defaultdict(list)
for id1, id2 in combis:
groups[id1].append(id2)
result = list(product(*groups.values()))

产生

[(1, 3, 5, 6), (1, 4, 5, 6), (2, 3, 5, 6), (2, 4, 5, 6)]
with combinationTable as (
select DENSE_RANK() over (Order By id1) as rn ,id2, id1 from test
)
select c1.id2,c2.id2,c3.id2
from combinationTable c1, combinationTable c2, combinationTable c3
where
c1.rn < c2.rn and
c2.rn < c3.rn
order by c1.rn,c2.rn,c3.rn

当然;From子句";以及";其中条款";如果您想选择4 id2而不是3 ,将被修改

最新更新