How to use COUNT in the same query with ROUND() and AVG()

oracleoracle-sql-developerplsql

I need to write a query where I need to first count the tickets sold for spectacles in a theater, then calculate the average number of tickets sold in each theater and to be round it to two decimal place and these values must to be sort by the number of tickets sold. In principle, I want to find the average number of tickets sold for each theater. For this query I must use AVG() and ROUND(). I tried so many different options, but I have different errors. When I tried to run this, this error appeared :

SQL Error: ORA-00937: not a single-group group function

SELECT
    t.id_theater
    , s.id_spectacle
    , ROUND((AVG(COUNT(tickets.id_ticket))), 2) average_tickets_theatre
FROM
    tickets tick
    , theater t
    , spectacles s
WHERE
    tick.id_spectacle = s.id_spectacle
    AND t.id_theater = s.id_theater
GROUP BY
    t.id_theater
    , s.id_spectacle
ORDER BY
    average_tickets_theatre

I tried to add the HAVING clause, but another error appeared:

SQL Error: ORA-00933: SQL command not properly ended

I'm sure that the problem consists in the fact that I'm trying to use COUNT with ROUND() and AVG(), but I really don't know what do to at this point and would appreciate any help.

Best Answer

The current version gives you an error because you're trying to get one aggregate function (average) over another one (count) ; it's not related to round. As far as I understand, you want to output id_theater, id_spectacle, count of tickets per theater and spectacle, and also average number of tickets per theater. One way (most likely not the fastest from performance perspective) would be

with t1 as 
(SELECT
    t.id_theater
    , s.id_spectacle
   , COUNT(tick.id_ticket) as num_tickets
   
FROM
    tickets tick
    , theater t
    , spectacles s
WHERE
    tick.id_spectacle = s.id_spectacle
    AND t.id_theater = s.id_theater
GROUP BY
    t.id_theater
    , s.id_spectacle
)
select  id_theater,id_spectacle , num_tickets, ROUND(avg(num_tickets) over (partition by id_theater),2) as avg_per_theater
from t1

Also, I'd suggest using ANSI-92 join instead of ANSI-89 syntax, it's way more readable