【问题标题】:SQL: JSON Extract from nested objectSQL:从嵌套对象中提取 JSON
【发布时间】:2021-06-10 23:53:37
【问题描述】:

我有一张这样的桌子

id obj
1 {"is_from_shopping_bag":true,"products":[{"price":{"amount":"18.00","currency":"USD","offset":100,"amount_with_offset":"1800"},"product_id":"1234","quantity":1}],"source":"cart"}
2 {"is_from_shopping_bag":false,"products":[{"price":{"amount":"80.00","currency":"USD","offset":100,"amount_with_offset":"8000"},"product_id":"2345","quantity":1}],"source":"pdp"}

我正在 Hive 中执行 sql 查询以获取“货币”字段。

目前我可以运行

SELECT
    JSON_EXTRACT( obj, '$.products')
FROM my_table

返回

obj
[{"price":{"amount":"18.00","currency":"USD","offset":100,"amount_with_offset":"1800"},"product_id":"1234","quantity":1}]
[{"price":{"amount":"80.00","currency":"USD","offset":100,"amount_with_offset":"8000"},"product_id":"2345","quantity":1}]

如何更深入地获得货币?

【问题讨论】:

    标签: sql hive


    【解决方案1】:

    获取第一个产品使用的货币:

    SELECT
        id,JSON_EXTRACT( obj, '$.products[0].price.currency') first_product_currency
    FROM my_table;
    
    id first_product_currency
    1 "USD"
    2 "USD"

    获取所有产品使用的货币:

    SELECT
        id,JSON_EXTRACT( obj, '$.products[*].price.currency') multiple_currencies
    FROM my_table;
    
    id multiple_currencies
    1 ["USD"]
    2 ["USD"]

    View on DB Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 2022-01-07
      • 2022-11-21
      相关资源
      最近更新 更多