snowflake cloud data platform - ARRAYS_TO_OBJECT with duplicate handling - Stack Overflow

ARRAYS_TO_OBJECT function merges two arrays into OBJECT.Returns an OBJECT that contains the keys specif

ARRAYS_TO_OBJECT function merges two arrays into OBJECT.

Returns an OBJECT that contains the keys specified by one input ARRAY and the values specified by another input ARRAY.

ARRAYS_TO_OBJECT( <key_array> , <value_array> )

SELECT ARRAYS_TO_OBJECT(['key1', 'key2', 'key3'], [1, 2, 3]);
{"key1": 1,"key2": 2, "key3": 3}  

The challenge is that the key_array cannot contain duplicates:

SELECT ['blue', 'green', 'blue', 'red'] AS arr1,
       [1,2,3,4]                        AS arr2,
       ARRAYS_TO_OBJECT(arr1, arr2)     AS result;
-- Error:
-- Duplicate field key 'blue'

On the other hand PARSE_JSON(expr, 'd') is capable of resolving duplicates:

Parameter Description
d Allow duplicate keys in JSON objects. If a JSON object contains a duplicate key, the returned object has a single instance of that key with the last value specified for that key.
s Don’t allow duplicate keys in JSON objects (strict). This value is the default.

ARRAYS_TO_OBJECT function merges two arrays into OBJECT.

Returns an OBJECT that contains the keys specified by one input ARRAY and the values specified by another input ARRAY.

ARRAYS_TO_OBJECT( <key_array> , <value_array> )

SELECT ARRAYS_TO_OBJECT(['key1', 'key2', 'key3'], [1, 2, 3]);
{"key1": 1,"key2": 2, "key3": 3}  

The challenge is that the key_array cannot contain duplicates:

SELECT ['blue', 'green', 'blue', 'red'] AS arr1,
       [1,2,3,4]                        AS arr2,
       ARRAYS_TO_OBJECT(arr1, arr2)     AS result;
-- Error:
-- Duplicate field key 'blue'

On the other hand PARSE_JSON(expr, 'd') is capable of resolving duplicates:

Parameter Description
d Allow duplicate keys in JSON objects. If a JSON object contains a duplicate key, the returned object has a single instance of that key with the last value specified for that key.
s Don’t allow duplicate keys in JSON objects (strict). This value is the default.

Seeking for SQL approach to handle merging two arrays with possible "duplicates" in the key_array.

Share Improve this question asked Mar 25 at 9:17 Lukasz SzozdaLukasz Szozda 177k26 gold badges273 silver badges314 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

ARRAYS_TO_OBJECT with duplicate handling can be emulated:

  • ARRAYS_ZIP - combine two arrays of the same size to an array of objects
  • REDUCE - reduce an array into a single object
  • OBJECT_INSERT - build an object with an active update flag

Code:

SELECT 
 ['blue', 'green', 'blue', 'red'] AS arr1,
 [1,2,3,4] AS arr2,
 REDUCE(ARRAYS_ZIP(arr1, arr2),{},(acc,x) -> OBJECT_INSERT(acc, x:$1::TEXT, x:$2, TRUE)) AS result;

Output:

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744207128a4563157.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信