views:

1503

answers:

4

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 ?

+5  A: 
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
Quassnoi
+1  A: 

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');
ammoQ
+1  A: 

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
Eoin Campbell
+1  A: 

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');
Tony Andrews