BigQuery:按表名分组

时间:2014-02-19 14:40:14

标签: google-bigquery

我的数据集(ds1)如下所示:

2014_01_01_tableA
2014_01_01_tableB

2014_01_02_tableA
2014_01_02_tableB

查询:

SELECT date, COUNT(1) AS counter 
FROM [ds1.2014_01_01_tableA], [ds1.2014_01_01_tableB], [ds1.2014_01_02_tableA], [ds1.2014_01_02_tableB] 
GROUP BY date;

返回:

date, counter
2014-01-01, 100
2014-01-02, 200

是否有可能按表名分组?这样的事可能吗? ...

SELECT date, COUNT(1) AS counter, TABLE_NAME() AS table_name
FROM [ds1.2014_01_01_tableA], [ds1.2014_01_01_tableB], [ds1.2014_01_02_tableA], [ds1.2014_01_02_tableB] 
GROUP BY table_name, date;

预期结果:

date, counter, table_name
2014-01-01, 50, 2014_01_01_tableA
2014-01-01, 50, 2014_01_01_tableB
2014-01-02, 100, 2014_01_02_tableA
2014-01-02, 100, 2014_01_02_tableB
不幸的是,

TABLE_NAME() AS table_name不存在。

2 个答案:

答案 0 :(得分:8)

不幸的是,没有办法干净利落地做到这一点。我添加了一个内部功能请求。

这种丑陋的方式是:

SELECT date, COUNT(1) AS counter, table_name
FROM 
 (SELECT *, "2014_01_01_tableA" as table_name FROM [ds1.2014_01_01_tableA]), 
 (SELECT *, "2014_01_01_tableB" as table_name FROM [ds1.2014_01_01_tableB]), 
 (SELECT *, "2014_01_02_tableA" as table_name FROM [ds1.2014_01_02_tableA]), 
 (SELECT *, "2014_01_02_tableB" as table_name FROM [ds1.2014_01_02_tableB])
GROUP BY table_name, date;

答案 1 :(得分:2)

现在可以使用_TABLE_SUFFIX参数和表格通配符。

SELECT date, COUNT(1) AS counter, _TABLE_SUFFIX as table_name
FROM `ds1.*`
WHERE _TABLE_SUFFIX IN ('2014_01_01_tableA', '2014_01_01_tableB', '2014_01_02_tableA', '2014_01_02_tableB')
GROUP BY table_name, date

_TABLE_SUFFIXFROM语句中通配符捕获的内容。它可以是部分表格后缀或完整的表格名称。例如,如果您使用FROM ds1.2014_01_*,则相应的_TABLE_SUFFIX将为01_tableA