0

我需要根据同一张表中的不同过滤器查询json字符串

CASE
    WHEN provider = 0 THEN JSON_VALUE_ARRAY (raw_data, '$.countries_served')
    WHEN provider = 1 THEN JSON_VALUE (raw_data,
'$.MerchantCountryISOAlpha3')
    WHEN provider = 2 THEN JSON_VALUE (raw_data, '$.operator.country.name')
    WHEN provider = 3 THEN JSON_VALUE (raw_data,
'$.countryName')
    WHEN provider = 4 THEN JSON_VALUE (raw_data, '$.countries')

CASE语句返回错误:

运营商 CASE 没有匹配的签名;所有 THEN/ELSE 参数都必须强制转换为通用类型,但可以找到:ARRAY、STRING;实际参数类型 (WHEN THEN) ELSE: (BOOL ARRAY) (BOOL STRING) (BOOL STRING) (BOOL STRING) (BOOL STRING) NULL at [6:3]

为什么会这样以及如何让它发挥作用?

4

1 回答 1

0

The issue here is that the first statement returns an ARRAY of countries, while all the other cases return a STRING with one country name.

The resulting column can only have one type, hence the error. To solve this you need to choose one type only, depending on what you intend to do with the data afterwards.

Maybe the most flexible option here would be to simply change JSON_VALUE_ARRAY function to JSON_QUERY: it returns a JSON-formatted string that still contains the array info:

WITH
  sample AS (
  SELECT 0 AS provider, '{"countries_served":["Japan", "France", "UK"]}' AS raw_data
  UNION ALL
  SELECT 4 AS provider, '{"countries":"Japan, France, UK"}' AS raw_data )

SELECT
  CASE
    WHEN provider = 0 THEN JSON_QUERY (raw_data, '$.countries_served')
    WHEN provider = 1 THEN JSON_VALUE (raw_data,'$.MerchantCountryISOAlpha3')
    WHEN provider = 2 THEN JSON_VALUE (raw_data, '$.operator.country.name')
    WHEN provider = 3 THEN JSON_VALUE (raw_data, '$.countryName')
    WHEN provider = 4 THEN JSON_VALUE (raw_data, '$.countries')
  END
  AS result
FROM
  sample

returns:

enter image description here

于 2022-01-27T11:04:32.510 回答