BigQuery:查找ID类型为RECORD的数组,并使用SQL从辅助表联接数据



我有一个如下的数据结构:

产品

| name  | region_ids             |
----------------------------------
| shoe  | c32, a43, x53          |
| hat   | c32, f42               |
# Schema
name                STRING  NULLABLE
region_ids          RECORD  REPEATED    
region_ids.value    STRING  NULLABLE    

区域

| _id |  name       |
---------------------
| c32 |  london     |
| a43 |  manchester |
| x53 |  bristol    |
| f42 |  liverpool  |
# Schema
_id                 STRING  NULLABLE
name                STRING  NULLABLE

我想查找";region_ids";并用区域名称替换它们,得到如下表:

| _id |  name  | region_names                |
----------------------------------------------
| d22 |  shoe  | london, manchester, bristol |
| t64 |  hat   | london, liverpool           |

使用标准SQL执行此操作的最佳方法是什么?

谢谢,

下面是BigQuery标准SQL

#standardSQL
SELECT p._id, p.name, 
STRING_AGG(r.name, ', ' ORDER BY OFFSET) AS region_names 
FROM `project.dataset.Products` p,
UNNEST(region_ids) WITH OFFSET
LEFT JOIN `project.dataset.Regions` r
ON value = r._id
GROUP BY _id, name   

你可以使用你的问题中的样本数据进行测试,如下面的示例所示

#standardSQL
WITH `project.dataset.Products` AS (
SELECT 'd22' _id, 'shoe' name, [STRUCT<value STRING>('c32'), STRUCT('a43'), STRUCT('x53')] region_ids UNION ALL
SELECT 't64', 'hat', [STRUCT<value STRING>('c32'), STRUCT('f42')]
), `project.dataset.Regions` AS (
SELECT 'c32' _id, 'london' name UNION ALL
SELECT 'a43', 'manchester' UNION ALL
SELECT 'x53', 'bristol' UNION ALL
SELECT 'f42', 'liverpool' 
)
SELECT p._id, p.name, 
STRING_AGG(r.name, ', ' ORDER BY OFFSET) AS region_names 
FROM `project.dataset.Products` p,
UNNEST(region_ids) WITH OFFSET
LEFT JOIN `project.dataset.Regions` r
ON value = r._id
GROUP BY _id, name   

结果是

Row _id name    region_names     
1   d22 shoe    london, manchester, bristol  
2   t64 hat     london, liverpool      

根据您问题中的输出示例-您希望region_names是一个字符串,其中包含逗号分隔的名称列表
但是,如果您需要region_names作为一个数组-您可以将STRING_AGG(r.name, ', ' ORDER BY OFFSET)替换为ARRAY_AGG(r.name ORDER BY OFFSET)

相关内容

  • 没有找到相关文章

最新更新