从BigQuery中的表中获取单个值和总和

时间:2016-05-08 14:35:29

标签: google-bigquery

假设在从更大的数据集中查询后,我有一个这样的表:

day   x   y
1     4   5
2     3   6
3     3   2
4     2   1
5     8   3

从那张表中我想得到从第1天开始的x和y的值,以及从所有日子到新表的x和y的总和。如何将结果放在一个包含两行而不是一行的表中?像这样:

         x    y
day1     4    5
days1-5  20   17

现在我能做的最好的就是:

SELECT 
    SUM(x) AS allx, 
    SUM(y) AS ally, 
    SUM(CASE WHEN day = 1 THEN x END) AS day1x, 
    SUM(CASE WHEN day = 1 THEN y END) AS day1y
FROM (
       ..
       ..
 )

我想有一种更聪明的方法可以做到这一点。

1 个答案:

答案 0 :(得分:2)

  

BigQuery - Legacy SQL:

使用comma style UNION ALL

SELECT 
  day, x, y 
FROM 
( SELECT 'day1' AS day, x, y 
  FROM YourTable
  WHERE day = 1 ),
( SELECT 
    CONCAT('day1-',STRING(COUNT(1))) AS day, 
    SUM(x) AS x, 
    SUM(y) AS y 
  FROM YourTable ) 

OR 使用ROLLUP

SELECT
  CONCAT('day_', IFNULL(STRING(day), 'all')) AS day, 
  x,
  y
FROM (
  SELECT 
    DAY, 
    SUM(x) AS x, 
    SUM(y) AS y 
  FROM YourTable
  GROUP BY ROLLUP(day)
)
WHERE IFNULL(day, 1) = 1
  

BigQuery - 标准SQL:

不要忘记取消选中显示选项

下的Use Legacy SQL复选框
SELECT 
  'day1' AS day, 
  x, 
  y 
FROM YourTable 
WHERE day = 1 
UNION ALL
SELECT 
  FORMAT('day1-%d', COUNT(1)) AS day, 
  SUM(x) AS x, 
  SUM(y) AS y 
FROM YourTable 

al的输出符合预期:

day     x   y    
day1    4   5    
day1-5  20  17