I am using treasure data for data analytics and having trouble with union statement in presto db.

How do i do a Union All on presto. I dont understand the documentation. everytime I try to do UNION like so:

SELECT COUNT(*) AS ReservationsCreated,resourceFROMreservationWHEREtype = 'create'UNIONSELECT COUNT(*) AS ReservationsDeleted,resourceFROMreservationWHEREtype = 'delete'GROUP BYresource;

I get output reformatted like:

SELECT COUNT(*) AS ReservationsCreated,resourceFROMreservationWHEREtype = 'create'UNIONSELECT COUNT(*) AS ReservationsDeleted,resourceFROMreservationWHEREtype = 'delete'GROUP BYresource;

and error that says:

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

I think I am not understanding the syntax for Presto. The docs are very confusing on Union. Any help appreciated.

1

Best Answer


The first part of the query is missing a group by as the error says.

 SELECT COUNT(*) AS ReservationsCreated, resourceFROM reservationWHERE type = 'create'group by resourceUNION ALLSELECT COUNT(*) AS ReservationsDeleted, resourceFROM reservationWHERE type = 'delete'GROUP BY resource

In fact, the query could be simplified to use conditional aggregation.

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 reservationsdeletedfrom reservationgroup by resource