gpt4 book ai didi

sql - Presto上的UNION ALL/UNION

转载 作者:行者123 更新时间:2023-12-02 07:24:59 28 4
gpt4 key购买 nike

我正在使用宝藏数据进行数据分析,并且在presto db中遇到合并声明有麻烦。

我如何做一个工会全部。我不了解文档。每当我尝试像这样做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上非常令人困惑。任何帮助表示赞赏。

最佳答案

如错误所述,查询的第一部分缺少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

关于sql - Presto上的UNION ALL/UNION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33660135/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com