如何按数组分组?

时间:2018-12-20 19:13:57

标签: sql postgresql

我下面有数据集:

id | object |
------------|
id1| object1|
id1| object2|
id1| object3|
id2| object1|
id2| object3|
id2| object4|
id3| object2|
id3| object3|
id3| object4|
id4| object1|
id4| object2|
id4| object3|
id5| object1| 
id5| object2|
id6| object1|
id6| object2|

我需要使用“对象”列按重复数据的数组进行分组:

object | count()
----------------
object1|   2   |<-from id1 and id4
object2|   2   |
object3|   2   |
----------------
object1|   2   |<-from id5 and id6
object2|   2   |
----------------
object1|   1   |<-from id2
object3|   1   |
object4|   1   |
----------------
object2|   1   |<-from id3
object3|   1   | 
object4|   1   |

如何将我的数据按巧合数组分组?

2 个答案:

答案 0 :(得分:2)

您似乎想根据ID的公共对象集来标识ID组。在第一个组中,ID 1和4与相同的三个对象1、2和3关联。

为此,第一步是唯一地标识每个组。在postgresql中,可以使用array_agg分析(窗口)功能执行此操作。一旦确定了组,您就可以按照以下SQL Fiddle中的数字计算相关ID:

查询1

with grp as (
  select id
       , object
       , array_agg(object) 
         over (partition by id order by object
               rows between unbounded preceding
                        and unbounded following) objs
   from YourData
)
select min(id) first_id
     , object
     , count(id) cnt
  from grp
 group by objs, object
order by cnt desc, first_id, object

Results

| first_id |  object | cnt |
|----------|---------|-----|
|      id1 | object1 |   2 |
|      id1 | object2 |   2 |
|      id1 | object3 |   2 |
|      id5 | object1 |   2 |
|      id5 | object2 |   2 |
|      id2 | object1 |   1 |
|      id2 | object3 |   1 |
|      id2 | object4 |   1 |
|      id3 | object2 |   1 |
|      id3 | object3 |   1 |
|      id3 | object4 |   1 |

答案 1 :(得分:1)

如果我理解正确,那么您需要这样的东西:

select objects, array_agg(id) as ids, count(*) as num_ids
from (select id, array_agg(object order by id) as objects
      from t
      group by id
     ) i
group by objects;