sqlamazon-athenaprestotrino

How to create an array by replacing values from another array?


I am looking for a way to create an array from another array based on the values of the second array with value mapping.

E.g. Table A has columns id, some_array and I have some value mapping in mind, says, {'a': 1, 'b': 2, 'c': 3} I want to do a select to get the array of mapping results from some_array

So, if A is

| id | some_array |
|:---|:-----------|
| 1  | ['a', 'b'] |
| 2  | ['a', 'c'] |

I need a query to generate following

| id | parsed_array |
|:---|:-----------|
| 1  | [1, 2]     |
| 2  | [1, 3      |

How can I achieve this query?

Thanks!


Solution

  • There are multiple ways of doing this, for example you can create a CTE containing mapping data, cross join it with the dataset and then use transform array function with MAP's element_at function (returns NULL if key is not present in the map) to map the data:

    -- sample data
    WITH dataset(id, some_array) as (
        values (1, array['a', 'b']),
        (2, array['a', 'c'])
    ),
    -- query parts    
    map_data(m) as (
        values (map(
                    array['a', 'b', 'c'],
                    array[1, 2, 3]
                ))
    )
    
    select id,
        transform(some_array, v -> element_at(m, v)) parsed_array 
    from dataset
    cross join map_data;
    

    Output:

    id parsed_array
    1 [1, 2]
    2 [1, 3]