Here's one possibility:
with departures(departure_id, cnt) as (
select f.departure_id, count(t.id_passenger)
from flight f
join takes t
on f.id = t.id_flight
where year(departure_date) = ?
group by f.departure_id
),
arrivals as (arrival_id, cnt) as (
select f.arrival_id, count(t.id_passenger)
from flight f
join takes t
on f.id = t.id_flight
where year(arrival_date) = ?
group by f.arrival_id
)
select position, max(cnt)
from (
select arrival_id as position, cnt
from arrivals
union
select departure_id as position, cnt
from departures
) as t;
Your additional calculated value:
(select count(t1.num) from T t1)
Is a scalar subquery, which is a dynamic rather than static expression. As such it's treated the same as a column as far as the aggregate is concerned and needs to be included in the group by clause to avoid the ORA-00937: not a single-group group function
error
However, oracle does not allow subqueries as part of the group by clause and trying to include the scalar subquery and/or the whole case statement:
group by (case (select count(*) cnt from t t1) when 0 then 1 else 0 end)
just results in an ORA-22818: subquery expressions not allowed here
error.
The only ways around this are to either convert your scalar subquery to an aggregate value like so:
max(case (select count(*) cnt from t t1) when 0 then 1 else 0 end)
or
(case max((select count(*) cnt from t t1)) when 0 then 1 else 0 end)
or rewrite your query to move the unaggregated scalar subquery out of the aggregated query:
select (case (select count(*) cnt from t t1) when 0 then 1 else 0 end) * sum
from (select sum(t3.num) sum from t t3) t2;
or precompute your scalar subquery so it can be used in the group by clause:
select case t1.cnt when 0 then 1 else 0 end * sum(t2.num)
from t t2
, (select count(*) cnt from t) t1
group by case t1.cnt when 0 then 1 else 0 end
Best Answer
Just use grouped
WHERE
conditions:Remember you really just want to get some boolean evaluations back here - as long as you can reduce your requirements to distinct sets of conditions you can put it into
WHERE
which will be plenty fast.The time to use
CASE
is if you have overlapping criteria that you need to short circuit.