2

我正在使用宝藏数据进行数据分析,并且在 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 的语法。文档对 Union 非常混乱。任何帮助表示赞赏。

4

1 回答 1

7

如错误所述,查询的第一部分缺少 a 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
于 2015-11-11T21:25:23.977 回答