我正在处理一个查询,该查询将根据是否找到表返回不同的结果。这是我的疑问:
SELECT
SUM(IF(COUNT(table_id) > 0, 1, 0)) AS found
FROM `table.__TABLES__`
WHERE table_id = 'app_events_20170207'
我遇到的问题是
错误:[2:3]
不允许聚合聚合
我可能错过了一些简单的东西,但似乎无法确定它。任何帮助都会很棒,谢谢!
最终产品将是基于是否找到表的查询,运行一个查询,如果不是,则运行另一个查询。
例如伪代码:
if (count(table_id) > 0, select * from table1, select * from table2)
答案 0 :(得分:2)
你有聚合聚合 - 这显然不起作用 另一方面,它看起来像你想要的 - 计算找到的表 - 很容易通过下面的
来实现SELECT
COUNT(table_id) AS found
FROM `table.__TABLES__`
WHERE table_id = 'app_events_20170207'
回答更新的问题
假设(select * from table1)和(select * from table2)的输出具有相同的模式 - 您可以使用类似下面的内容
#standardSQL
WITH switch AS (
SELECT
COUNT(table_id) AS found
FROM `table.__TABLES__`
WHERE table_id = 'app_events_20170207'
)
SELECT * FROM table1 WHERE ((SELECT MAX(found) FROM switch) > 0)
UNION ALL
SELECT * FROM table2 WHERE ((SELECT MAX(found) FROM switch) = 0)
您可以使用以下虚拟数据检查其行为:
#standardSQL
WITH table1 AS (
SELECT 1 AS a, 2 AS b
),
table2 AS (
SELECT 3 AS a, 4 AS b
),
switch AS (
SELECT
COUNT(table_id) AS found
FROM `table.__TABLES__`
WHERE table_id = 'app_events_20170207'
)
SELECT * FROM table1 WHERE ((SELECT MAX(found) FROM switch) > 0)
UNION ALL
SELECT * FROM table2 WHERE ((SELECT MAX(found) FROM switch) = 0)