从具有列名称的行获取MAX(SQL)

时间:2015-05-30 07:14:50

标签: google-bigquery

很抱歉,如果我的任务很简单,但我花了一天时间用Google搜索,但仍然无法弄清楚如何解决这个问题:

我的表格如下:

userId A B C D E
  1    5 0 2 3 2
  2    3 2 0 7 3

我需要每行每个MAX列名:

userId MAX
  1     A
  2     D

所有想法将不胜感激!谢谢! 我使用谷歌大查询,所以我的理解可能与MySQL不同,但如果你有MySQL的想法,我会尝试翻译。

2 个答案:

答案 0 :(得分:7)

您可以使用GREATEST

SELECT userid, CASE GREATEST(A,B,C,D,E)
                    WHEN A THEN 'A'
                    WHEN B THEN 'B'
                    WHEN C THEN 'C'
                    WHEN D THEN 'D'
                    WHEN E THEN 'E'
               END AS MAX
FROM TableName

结果:

userId  MAX
1       A
2       D

使用示例表,它看起来像:

SELECT userid, CASE GREATEST(A,B,C,D,E) 
                    WHEN A THEN 'A'                        
                    WHEN B THEN 'B'
                    WHEN C THEN 'C'
                    WHEN D THEN 'D'
                    WHEN E THEN 'E'
               END AS MAX
from (select  1 as userId,   5 as A, 0 as B, 2  as C, 3 as D, 2 as E),
(select  2 as userId,   3 as A, 2 as B, 0  as C, 7 as D, 3 as E)

答案 1 :(得分:0)

以下是用于BigQuery标准SQL

#standardSQL
SELECT *, 
  ( SELECT key
    FROM UNNEST(REGEXP_EXTRACT_ALL(TO_JSON_STRING(t), r'".*?":[^,}]*')) kv,
    UNNEST([STRUCT(TRIM(SPLIT(kv, ':')[OFFSET(0)], '"') AS key, SAFE_CAST(SPLIT(kv, ':')[OFFSET(1)] AS INT64) AS value)])
    WHERE key != 'userId'
    ORDER BY value DESC
    LIMIT 1
  ) max_column
FROM `project.dataset.table` t     

是否适用于以下示例中的问题样本数据

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 userId, 5 A, 0 B, 2 C, 3 D, 2 E UNION ALL
  SELECT 2, 3, 2, 0, 7, 3 UNION ALL
  SELECT 3, 1, 2, NULL, 4, 5
)
SELECT *, 
  ( SELECT key
    FROM UNNEST(REGEXP_EXTRACT_ALL(TO_JSON_STRING(t), r'".*?":[^,}]*')) kv,
    UNNEST([STRUCT(TRIM(SPLIT(kv, ':')[OFFSET(0)], '"') AS key, SAFE_CAST(SPLIT(kv, ':')[OFFSET(1)] AS INT64) AS value)])
    WHERE key != 'userId'
    ORDER BY value DESC
    LIMIT 1
  ) max_column
FROM `project.dataset.table` t   

输出是

Row     userId  A       B       C       D       E       max_column   
1       1       5       0       2       3       2       A    
2       2       3       2       0       7       3       D    
3       3       1       2       null    4       5       E