Raoul
Raoul

Reputation: 3899

Oracle - return multiple counts as one query

I have a couple of queries, detailed below. I'd like to be able to run one SQL query which returns both counts, is this possible?

1.

select nvl(count(rowid), 0) from tablename where OPP = 'FOO' and date = 'BAZ';

2.

select nvl(count(rowid), 0) from tablename where OPP = 'BAR' and date = 'BAZ';

I've only found MSSQL specific solutions in my searches so far.

Upvotes: 13

Views: 30789

Answers (3)

Álvaro González
Álvaro González

Reputation: 146470

If you need them in a single row:

SELECT
    COUNT(CASE OPP WHEN 'FOO' THEN 1 END),
    COUNT(CASE OPP WHEN 'BAR' THEN 1 END)
FROM tablename
WHERE OPP IN ('FOO', 'BAR') AND date = 'BAZ'

(The GROUP BY approach by Thilo is a better generic solution anyway.)

Edit: I've removed NVL(). I had forgotten why I never use it.

Upvotes: 11

Thilo
Thilo

Reputation: 262684

If the condition really looks like that (same table, only one field different in the groups):

select opp, count(*) from tablename
where date = 'BAZ'
group by opp
having opp in ('FOO', 'BAR');

For arbitrary queries:

select 'A', count(*) from tableA
union all
select 'B', count(*) from tableB

Upvotes: 8

Denis de Bernardy
Denis de Bernardy

Reputation: 78513

You could use a with statement:

with
count1 as (
select ...
),
count2 as (
select ...
)
select tot1, tot2
from count1, count2

Upvotes: 4

Related Questions