Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Athena SQL – Unable to UNNEST JSON string as desired

I’ve JSON string in Athena as follows:

[{name=agreementUrl, value=agmt-id00001}, {name=sellerOfRecord, value=ABC Corporation}]
[{name=agreementUrl, value=agmt-id00002}, {name=sellerOfRecord, value=XYZ Corporation}]

I’m trying to get the values of Agreement ID in separate columns Agreement ID and sellerOfRecord. With the below query I was able to get these values out but these comes in separate rows. How can I get the agreement ID and corresponding vendor in the same result record?

SELECT
license_metadata.name,license_metadata.value
FROM
  json_licensedata
CROSS JOIN UNNEST(licensemetadata) t (license_metadata)
name value
agreementUrl agmt-id00001
sellerOfRecord ABC Corporation
agreementUrl agmt-id00002
sellerOfRecord XYZ Corporation

Expected Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Agreement ID sellerOfRecord
agmt-id00001 ABC Corporation
agmt-id00002 XYZ Corporation

>Solution :

You can apply the conditional aggregation on the dataset produced by your query :

SELECT MAX(CASE WHEN name = 'agreementUrl' THEN value END) as AgreementID,
       MAX(CASE WHEN name = 'sellerOfRecord' THEN value END) as sellerOfRecord
FROM (
  SELECT licensemetadata, license_metadata.name, license_metadata.value
  FROM json_licensedata
  CROSS JOIN UNNEST(licensemetadata) t (license_metadata)
) as s
GROUP BY licensemetadata
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading