BigQuery:将多个字段汇总到数组中

BigQuery: Aggregate multiple fields into array

我有一些数据,每个ID要将两个或多个字段聚合到一个数组中,并且希望它们按顺序匹配。

因此,例如,如果我有以下数据:

enter image description here

我想把它变成这样:

enter image description here

另外,这样的事情也可以:

enter image description here

因此,首先,如果我使用这样的查询,它将执行我想要的操作,还是不能保证两个字段以相同的顺序通过(即Value_1和Value_2中的对应值可能不匹配)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
SELECT
  ID,
  ARRAY_AGG (
    Value_1
  ) AS Value_1,
  ARRAY_AGG (
    Value_2
  ) AS Value_2

FROM
  table

GROUP BY
  ID

如果没有,我该怎么做?


如果要将值配对在一起,请使用ARRAY_AGGSTRUCT。 例如,

1
2
3
4
5
6
7
8
9
SELECT
  ID,
  ARRAY_AGG (
    STRUCT(Value_1, Value_2)
  ) AS Values
FROM
  table
GROUP BY
  ID;

...并且对于您的alternative询问:

1
2
3
4
5
SELECT  
  id,
  ARRAY_AGG(CONCAT('[', Value_1, ',', Value_2, ']')) AS Values
FROM `yourTable`
GROUP BY id

使用Python BigQuery的Array_Agg ()的工作解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
!pip install -U google-cloud-bigquery
import pandas as pd

from google.cloud import bigquery

strvalue ="""SELECT users ARRAY_AGG(STRUCT(session, page )) as hasComp FROM <datasetname>.<tableName> WHERE Group by users order by users limit 100"""

bigquery_client = bigquery.Client(project="")

dataset = bigquery_client.dataset("")

table = dataset.table('')

table.view_query_legacy_sql = False

query_job = bigquery_client.query(str_value)

df = query_job.to_dataframe()

print(df)