Presto上的UNION ALL / UNION

时间:2015-11-11 21:23:54

标签: sql bigdata union presto treasure-data

我正在使用宝藏数据进行数据分析,并且在presto db中遇到了union语句的问题。

我如何在presto上做一个Union All。我不明白文档。每次我都尝试这样做UNION:

SELECT 
  COUNT(*) AS ReservationsCreated,
  resource
FROM
  reservation
WHERE
  type = 'create'
UNION
SELECT 
  COUNT(*) AS ReservationsDeleted,
  resource
FROM
  reservation
WHERE
  type = 'delete'
GROUP BY
  resource
;

我得到的输出重新格式化为:

SELECT 
  COUNT(*) AS ReservationsCreated,
  resource
FROM
  reservation
WHERE
  type = 'create'
UNION
SELECT 
COUNT(*) AS ReservationsDeleted,
resource
FROM
reservation
WHERE
type = 'delete'
GROUP BY
resource
;

并出现错误:

'"resource"' must be an aggregate expression or appear in GROUP BY clause

我想我不理解Presto的语法。联盟上的文档非常令人困惑。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:6)

如错误所示,查询的第一部分缺少group by

 SELECT COUNT(*) AS ReservationsCreated, resource
 FROM reservation
 WHERE type = 'create'
 group by resource
 UNION ALL
 SELECT COUNT(*) AS ReservationsDeleted, resource
 FROM reservation
 WHERE type = 'delete'
 GROUP BY resource

实际上,可以简化查询以使用条件聚合。

select 
 resource
,sum(case when type = 'create' then 1 else 0 end) as reservationscreated
,sum(case when type = 'delete' then 1 else 0 end) as reservationsdeleted
from reservation
group by resource