首页 > 解决方案 > 如何在 SQL 中对列进行 GROUP BY 组合?

问题描述

假设我有一张如下表,

Date         |Student ID| Building 
2019-01-01   | 1        |    A
2019-01-01   | 1        |    B
2019-01-01   | 1        |    C
2019-01-01   | 2        |    B
2019-01-01   | 2        |    C
2019-01-01   | 3        |    C
2019-01-01   | 3        |    B
2019-01-01   | 4        |    B

如何按每个学生访问的建筑物的独特组合进行分组?到目前为止,我的方法是 GROUP BY Date, Student ID, Building 对它们进行排序,然后我尝试连接具有相同日期和学生 ID 的行,但还不知道这样做。总之,我正在努力实现这张桌子,

Date         |Student ID| Building 
2019-01-01   | 1        | A, B, C
2019-01-01   | 2        |  B, C
2019-01-01   | 3        |  B, C
2019-01-01   | 4        |    B

我是 SQL 新手(我为此使用 Google BigQuery),欢迎提供任何提示

标签: sqlgoogle-bigquery

解决方案


您可以使用string_agg()array_agg()

select date, student_id, string_agg(building, ', ')
from t
group by date, student_id;

在 BigQuery 中,虽然您通常会使用数组:

select date, student_id, array_agg(building)
from t
group by date, student_id;

如果可以有重复项,请distinct在函数中使用。如果您想要特定顺序的行,请使用order by. 就像是:

select date, student_id, array_agg(distinct building order by building)
from t
group by date, student_id;

推荐阅读