15

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.

4
  • 1
    No need for the nvl, count will never return null. Commented Jun 15, 2011 at 10:57
  • are you wanting to run these through SQLPlus? Toad? as a Stored Proc? Commented Jun 15, 2011 at 10:59
  • Do you want the two counts in one row as columns? Or do you want two rows? Commented Jun 15, 2011 at 11:00
  • @Cos Callis I want to run this with Toad for testing, then with Perl DBI as part of a larger Perl script Commented Jun 15, 2011 at 11:00

3 Answers 3

12

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.)

Sign up to request clarification or add additional context in comments.

Comments

9

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

1 Comment

This should be the accepted answer since this is the correct approach
4

You could use a with statement:

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

2 Comments

If I run this as is, except with a valid select clause, I get 'tot2' invalid identifier. This is Oracle 10G btw
That would be the names of your column aliases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.