2

I have the following two PL/SQL Oracle Queries that return a count:

SELECT count(*)
  INTO counter_for_x
  FROM Table_Name
 WHERE Column_Name = 'X';

SELECT count(*)
  INTO counter_for_y
  FROM Table_Name
 WHERE Column_Name = 'Y';

Is it possible to write a single query that returns both the counts and populates the respective counter variables ?

4 Answers 4

8
SELECT  (
        SELECT COUNT(*)
        FROM   table_name
        WHERE  column_name = 'X'
        ),
        (
        SELECT COUNT(*)
        FROM   table_name
        WHERE  column_name = 'Y'
        )
INTO    counter_for_x, counter_for_y
FROM    dual
Sign up to request clarification or add additional context in comments.

Comments

1

You can, but I wouldn't do it...

select nvl(sum(decode(column_name,'X',1,0)),0), nvl(sum(decode(column_name,'Y',1,0)),0)
  into counter_for_x, counter_for_y
  from table_name
  where column_name in ('X', 'Y');

Comments

1

Another way.

SELECT
   Max(CASE WHEN Column_Name = 'X' THEN Count ELSE NULL END) AS Count_X ,
   MAX(CASE WHEN Column_Name = 'Y' THEN Count ELSE NULL END) AS Count_Y
FROM
(
    SELECT count(*) as Count, Column_Name
    FROM Table_Name
    Where Column_Name in ('X', 'Y')
    Group By Column_Name
) AS InnerTable

Comments

1

This will do it:

select count(decode(column_name,'X',1)) x_count
,      count(decode(column_name,'Y',1)) y_count
into   counter_for_x, counter_for_y
from   table_name
where  column_name in ('X','Y');

or if you prefer using CASE:

select count(case when column_name = 'X' then 1 end) x_count
,      count(case when column_name = 'Y' then 1 end) y_count
into   counter_for_x, counter_for_y
from   table_name
where  column_name in ('X','Y');

Comments

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.