单个选择中的Bigquery多个不需要的东西

时间:2017-08-08 04:41:15

标签: google-bigquery

跟进此事 - Bigquery combining repeated fields from 2 different tables

@ElliottBrossard的上述解决方案正是我所寻找的。谢谢!我需要取消上面的字段以获得学生的聚合。比如说,还有一个额外的费用字段(每门课程)例如假设在student_courses表中输出以上内容,我需要做类似的事情,

SELECT
  COUNT(DISTINCT phone.number),
  COUNT(DISTINCT courses.Id),
  SUM(courses.Cost)
FROM
  student_courses,
  UNNEST(phone),
  UNNEST(courses)

我从上面得到的预期答案是3,4,800美元(假设4门课程每门花费200美元)。上述查询最终表现为交叉连接。是否可以使用单个Select来从多个巢中获取聚合?

1 个答案:

答案 0 :(得分:1)

这是一个想法,虽然它有点冗长:

#standardSQL
SELECT
  (SELECT COUNT(DISTINCT number)
   FROM UNNEST(numbers) AS number),
  (SELECT COUNT(DISTINCT course_id)
   FROM UNNEST(course_ids) AS course_id),
  course_sum
FROM (
  SELECT
    ARRAY_CONCAT_AGG(
      ARRAY(SELECT number FROM UNNEST(phone))
    ) AS numbers,
    ARRAY_CONCAT_AGG(
      ARRAY(SELECT id FROM UNNEST(courses))
    ) AS course_ids,
    SUM((SELECT SUM(cost) FROM UNNEST(courses))) AS course_sum
  FROM YourTable
);

参考文献: