如何根据一个特定列中的值对行进行分组?

时间:2016-10-28 02:09:37

标签: postgresql group-by data-cleaning

假设我有一组数据,例如

  

(student_id ,,,,, topic_of_interests)

现在,兴趣的主题可以从远足,阅读和睡眠不等。我需要根据这些兴趣主题对学生进行分组,每个学生在topic_of_interests中都有多个以逗号分隔的条目。我该怎么做呢?

我需要的最终结果是一个映射,这样查询一个感兴趣的主题就会给我所有与之相关的学生。 编辑:数据非常大,我不知道不同兴趣主题的价值。

1 个答案:

答案 0 :(得分:1)

这是一种经典的多对多关系。 您需要两个主要表studentstopics和一个所谓的桥接表(或映射):

create table students_topics (
    student_id int references students,
    topic_id int references topics,
    primary key (student_id, topic_id)
);

请参阅full example in rextester

如果您想轻松获得此类分析,则应将实际表格重建为上述模型。

使用您的实际数据结构尝试此方法:

select topic, array_agg(student_id)
from (
    select student_id, trim(topic) topic
    from students, 
    unnest(string_to_array(topic_of_interests, ',')) topic
    ) s
group by 1;
相关问题