Alex Fox
Alex Fox

Reputation: 1225

BigQuery: Lookup array of IDs and join data from secondary table using SQL

I have a data structure like below:

Products

| _id |  name  | available_in_region_id |
-----------------------------------------
| d22 |  shoe  | c32, a43, x53          |
| t64 |  hat   | c32, f42               |

Regions

| _id |  name       |
---------------------
| c32 |  london     |
| a43 |  manchester |
| x53 |  bristol    |
| f42 |  liverpool  |

I want to look up the array of "available_in_region_id" ids and replace them by the region name to result in a table like below:

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

What is the best way to do this using standard SQL?

Thanks,

A

Upvotes: 0

Views: 416

Answers (1)

Mikhail Berlyant
Mikhail Berlyant

Reputation: 173121

Below is for BigQuery Standard SQL

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

You can test, play with above using sample data from your question as in below example

#standardSQL
WITH `project.dataset.Products` AS (
  SELECT 'd22' _id, 'shoe' name, 'c32, a43, x53' available_in_region_id UNION ALL
  SELECT 't64', 'hat', 'c32, 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 available_in_region_name
FROM `project.dataset.Products` p,
UNNEST(SPLIT(available_in_region_id, ', ')) rid WITH OFFSET
LEFT JOIN `project.dataset.Regions` r
ON rid = r._id
GROUP BY _id, name  

with output

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

Upvotes: 2

Related Questions