简体   繁体   中英

Subtract elements of 1st array from 2nd AWS Athena

I have a table with the below schema

 test_name, subject_1, subject_2

It has entries like

  ('A',['a','b','c'],['b','d']),('B',['d','a','b'],['a','b']),etc

Now, I wish to perform set subtraction like set(subject_1)-set(subject_2). So, for 'A', output will be ['a','c']. For 'B', ['d'].

Any help.! I tried searching the internet but in vain.

In Athena / Presto the sets are based on Array.

WITH example_table AS
 (SELECT 'A' AS test_name, ARRAY['a','b','c'] AS subject_1, ARRAY['b','d'] AS subject_2 UNION ALL
  SELECT 'B', ARRAY['d','a','b'], ARRAY['a','b'] )

SELECT test_name, 
       array_except(
             subject_1,
             array_intersect(subject_1,subject_2)
       ) AS diff
FROM example_table

  • The WITH part is used to create the temp table for the main query.
  • The Diff is a combination of array_intersect and array_except

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM