sql - 如何在 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),欢迎提供任何提示
解决方案
您可以使用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;
推荐阅读
- javascript - 如何在解构与抛出错误中返回 null
- javascript - 如何从 span 中获取每个值并使用 js 或 jquery 将所有值设置为变量?
- python-3.x - 在从独立 pyinstaller exe 中存在的 tkinter 启动的命令提示符下运行 python 函数
- javascript - 是否可以在 JavaScript 调试器中查看对象的构造位置?
- python - 如何使用 Python 将文本内容旁边的多个图像发送到 Discord 频道?
- javascript - 无法让我的 if 语句在“app.post”函数中工作
- arrays - 为什么我不能从文本文件中连接重建和数字数组 c char 的内容?
- python - 使用 lxml python 解析时输出错误
- haskell - 堆栈:检测到随机依赖循环
- qt - 无法引用 listview qml 的突出显示 id