按 BigQuery 中列段的最大值返回列名称

swm*_*swm 1 sql google-bigquery

我的查询应该根据列的最大值返回列名称。我尝试使用 CASE WHEN 来解决这个问题。但不知怎的,这个错误发生了,可能是因为我返回列的名称而不是列本身的值:

No matching signature for operator CASE; all THEN/ELSE arguments must be coercible to a common type but found: INT64, STRING; actual argument types (WHEN THEN) ELSE: (BOOL STRING) (BOOL INT64) INT64 at [3:5]
Run Code Online (Sandbox Code Playgroud)

我的代码是:

SELECT
ID,
    CASE
        WHEN col1 >= col2 AND col1 >= col3 AND col1 >= col4 AND col1 >= col5 THEN 'col1 '
        WHEN col2 >= col1 AND col2 >= col3 AND col2 >= col4 AND col2 >= col5 THEN 'col2 '
        ELSE 'col1'                                
    END AS Max_Column_Name
FROM table
Run Code Online (Sandbox Code Playgroud)

输入示例为:

在此输入图像描述

有什么办法可以让这个查询变得更简单吗?因此,如果有很多列,则无需重复when..case。其他举措是像这篇文章中那样使用 GREATEST(col1,col2,col3) ,但是,我不确定如何在标准 sql、bigquery 中使用它。

预期输出:

返回每个细分(国家、产品、语言)具有最大值的列的名称,并重命名表结果中的列的名称。

在此输入图像描述

Gor*_*off 8

假设您没有NULL值,您可以使用greatest()

select (case greatest(country_uk, country_us)
            when country_uk then 'uk' when country_us then 'us'
        end), 
       . . .
Run Code Online (Sandbox Code Playgroud)

您还可以使用数组:

select (select el.what
        from unnest(array['uk' as what, country_uk as val), ('us', country_us)]) el
        order by el.val desc
        limit 1
       ) as country
Run Code Online (Sandbox Code Playgroud)