Tho*_*asW 2 sql google-bigquery
假设我有一个包含以下信息的 BQ 表
| ID | 测试名称 | 测试成绩 |
|---|---|---|
| 1 | A | 5 |
| 乙 | 7 | |
| 2 | A | 8 |
| C | 3 |
测试嵌套的地方。我如何将测试转移到下表中?
| ID | A | 乙 | C |
|---|---|---|---|
| 1 | 5 | 7 | |
| 2 | 8 | 3 |
pivot(test)我无法直接进行透视测试,因为我在:处收到以下错误消息Table-valued function not found。前面的问题(1、2)不处理嵌套列或者已经过时。
以下查询看起来是有用的第一步:
select a.id, t
from `table` as a,
unnest(test) as t
Run Code Online (Sandbox Code Playgroud)
然而,这只是为我提供了:
| ID | 测试名称 | 测试成绩 |
|---|---|---|
| 1 | A | 5 |
| 1 | 乙 | 7 |
| 2 | A | 8 |
| 2 | C | 3 |
条件聚合是一个好方法。如果您的表很大,您可能会发现这具有最佳性能:
select t.id,
(select max(tt.score) from unnest(t.score) tt where tt.name = 'a') as a,
(select max(tt.score) from unnest(t.score) tt where tt.name = 'b') as b,
(select max(tt.score) from unnest(t.score) tt where tt.name = 'c') as c
from `table` t;
Run Code Online (Sandbox Code Playgroud)
我推荐这样做的原因是因为它避免了外部聚合。这种unnest()情况的发生无需打乱数据——而且我发现这在性能方面是一个巨大的胜利。
| 归档时间: |
|
| 查看次数: |
3844 次 |
| 最近记录: |