是否可以在Google Bigquery中将记录(或行)移动到不需要的位置

时间:2018-02-27 12:20:36

标签: google-bigquery

在Google bigquery中,是否可以将每条记录(行)移到不需要的位置?

例如,

Name    Physics Chemistry   Maths   Biology
John    94      85          86      65
James   97      86          84      54
David   90      82          76      45

我想将每条记录移到不需要的位置(如下例所示)。如何将每一行移到不需要的位置?

SELECT MAX(x)AS max 来自UNNEST([94,85,86,65,])AS x;

提前致谢

2 个答案:

答案 0 :(得分:2)

您可以将问题建模为包含两列的表格,NameSTRINGGrades为整数数组:

WITH School AS (
SELECT 'John' Name, [94, 85, 86, 65] Grades UNION ALL
SELECT 'James', [97, 86, 84, 54] UNION ALL
SELECT 'David', [90, 82, 76, 45]
)
SELECT Name, (SELECT MAX(Grade) FROM UNNEST(Grades) Grade) BestGrade 
FROM School

将产生:

Name    BestGrade
=================
John    94
James   97
David   90

更新:如果我们还希望同时显示最佳成绩和成绩的科目,我们应该将数据建模略有不同。假设不同的学生在学校上学不同的课程,而不是每个科目保留严格的专栏,我们可以将成绩建模为ARRAY<STRUCT<Subject STRING, Grade INT64>>,然后解决方案将如下:

WITH School AS (
SELECT 'John' Name, array<struct<Subject string, Grade int64>>[('Physics', 94), ('Chemistry', 85), ('Math', 86), ('Biology', 65)] Grades UNION ALL
SELECT 'James', array<struct<Subject string, Grade int64>>[('Math', 97), ('Orchestra', 86), ('Spanish', 84)] UNION ALL
SELECT 'David', array<struct<Subject string, Grade int64>>[('History', 90), ('Spanish', 82), ('Chemistry', 76), ('Physics', 45)]
)
SELECT 
  Name,
 (SELECT Grade FROM UNNEST(Grades) Grade
  ORDER BY Grade.Grade DESC LIMIT 1) BestGrade
FROM School

这将产生:

Name    BestGrade.Subject   BestGrade.Grade
===========================================
John    Physics             94
James   Math                97
David   History             90

答案 1 :(得分:2)

以下是BigQuery Standard SQL

注意:此解决方案使用原始表架构,因为它有问题(有时很难更改/控制给您的内容,因此您需要使用它,因为它 :o))并且它不依赖于主题/列的数量和名称

   
#standardSQL
WITH `project.dataset.scores` AS (
  SELECT 'John' Name, 94 Physics, 85 Chemistry, 86 Maths, 65 Biology UNION ALL
  SELECT 'James', 97, 86, 84, 54 UNION ALL
  SELECT 'David', 90, 82, 76, 45 
)
SELECT 
  Name,   
  BestGrade.*
FROM `project.dataset.scores` t, UNNEST(
  ARRAY(
    SELECT AS STRUCT 
      SPLIT(REGEXP_REPLACE(kv, r'[{"}]', ''), ':')[OFFSET(0)] Subject,
      SAFE_CAST(SPLIT(REGEXP_REPLACE(kv, r'[{"}]', ''), ':')[OFFSET(1)] AS INT64) Grade
    FROM UNNEST(SPLIT(TO_JSON_STRING(t), ',"')) kv
    ORDER BY Grade DESC
    LIMIT 1
  )
) BestGrade  

结果为

Row Name    Subject     Grade    
1   John    Physics     94   
2   James   Physics     97   
3   David   Physics     90