首页 > 解决方案 > 从具有多个值的字段中检索数据

问题描述

我们有餐桌人。它具有具有多个值的示例字段,例如

人

ID 名称 tripNumber startPlace endPlace
1 xxx 20 波特兰亚特兰大
          25 加利福尼亚 亚特兰大
          40 美洲 非洲
2 EKVV 40 美洲 非洲
          37 阿根廷 卡罗来纳

我们需要在特定条件下检索整行数据,例如 tripNumber=40 和 endPlace="Africa"

我们需要这样的结果,

ID 名称 tripNumber startPlace endPlace
1 xxx 40 美洲 非洲
2 EKVV 40 美洲 非洲

标签: google-bigquery

解决方案


以下是 BigQuery 标准 SQL

#standardSQL
WITH `project.dataset.person` AS (
  SELECT 1 id, 'xxx' name, [20, 25, 40] tripNumber, ['Portland', 'California', 'America'] startPlace, ['Atlanta', 'Atlanta', 'Africa'] endPlace UNION ALL
  SELECT 2,  'EKVV', [40, 37], ['America', 'Argentina'], ['Africa', 'Carolina']
)
SELECT id, name, tripNumber, startPlace[SAFE_OFFSET(off)] startPlace, endPlace[SAFE_OFFSET(off)] endPlace 
FROM `project.dataset.person`,
UNNEST(tripNumber) tripNumber WITH OFFSET off
WHERE tripNumber = 40

结果

Row id  name    tripNumber  startPlace  endPlace     
1   1   xxx     40          America     Africa   
2   2   EKVV    40          America     Africa     

上述解决方案假设您有独立的重复字段并根据各自数组中的位置进行匹配

以下 - 基于更常见的重复记录模式

所以如果person表格如下所示

Row id  name    trips.tripNumber    trips.startPlace    trips.endPlace   
1   1   xxx     20                  Portland            Atlanta  
                25                  California          Atlanta  
                40                  America             Africa   
2   2   EKVV    40                  America             Africa   
                37                  Argentina           Carolina        

在这种情况下,解决方案是

#standardSQL
WITH `project.dataset.person` AS (
  SELECT 1 id, 'xxx' name, [STRUCT<tripNumber INT64, startPlace STRING, endPlace STRING>(20, 'Portland', 'Atlanta'),(25, 'California', 'Atlanta'),(40, 'America', 'Africa')] trips UNION ALL
  SELECT 2, 'EKVV', [STRUCT(40, 'America', 'Africa'),(37, 'Argentina', 'Carolina')]
)
SELECT id, name, tripNumber, startPlace, endPlace 
FROM `project.dataset.person`,
UNNEST(trips) trip
WHERE tripNumber = 40 

结果

Row id  name    tripNumber  startPlace  endPlace     
1   1   xxx     40          America     Africa   
2   2   EKVV    40          America     Africa   

推荐阅读