views:

142

answers:

4
+2  Q: 

complex sql query

There is a customer table. I want to list active and deactive status in one query. How can I do this ?

SELECT count(*) as ACTIVE, 
count(*) as DEACTIVE 
FROM V_CUSTOMER 
WHERE STATUS='a' AND STATUS='d' 
+4  A: 

Try using group by:

SELECT count(*), STATUS FROM V_CUSTOMER
Where STATUS='a' OR STATUS='d'
GROUP BY STATUS
krock
+1: This is the best answer
OMG Ponies
this will count all recods active + deactive but i think he need seprate count of active and deactive
Pranay Rana
@Jack - this solution returns two rows whereas the solution proposed by Pranay will give you the two counts in a single row, which is want you asked for.
APC
@APC, OP asked for one query not one row, IMO this solution would be easy to maintain if for instance you wanted to include another status or remove the where clause and get count for each status.
krock
Well, I still think Pranay's solution is th ecloser to what was requested (it was the one I would have supplied if I had been a fatser typist). As for maintainability, YAGNI applies to SQL statements as much as any other code. We should strive for the most appropriate solution for now, and not worry about putative future requirements until they materialize.
APC
+5  A: 

We can use CASE statement to translate the two values of STATUS:

SELECT 
    sum(case when STATUS = 'a' then 1 else 0 end) as ACTIVE 
    , sum(case when STATUS = 'd' then 1 else 0 end) as DEACTIVE 
FROM V_CUSTOMER 

There is no need for a WHERE clause unless there are a large number of records with other values for STATUS, in which case use OR instead of AND:

WHERE STATUS='a' OR STATUS='d'         
Pranay Rana
I think `case when` is sql server, not oracle?
Stefan Steinegger
@StefanSteinegger - Oracle has supported CASE in SELECT statements since 8i (i.e. for more than a decade)
APC
i found this link :http://www.techonthenet.com/oracle/functions/case.php
Pranay Rana
thanks @APC for updated answer
Pranay Rana
wonder y wrong answer get selected ?
Pranay Rana
+1 I prefer this solution because it is the closest to the OP's request, as it returns a single row.
APC
@pranay: sorry, didn't know that. Who's "wrong answer had been selected"?
Stefan Steinegger
no need to sorry it happens sometime
Pranay Rana
@pranay, as I have stated you have misread the question if you consider my answer wrong. OP wanted the result in one *query*, **not** one *row*. The amount of rows that is returned is inconsequential.
krock
@krock no problem -- anyway tanks -- its ok
Pranay Rana
+1  A: 

I think you'll need something like this:

select Status, count(*) from V_Customer
where STATUS='a' or STATUS='d'
group by STATUS

This will give you the number of records per status.

PeterEysermans
+3  A: 
SELECT count(decode(status,'a',1)) as ACTIVE, 
count(decode(status,'d',1)) as DEACTIVE 
FROM V_CUSTOMER 
WHERE STATUS='a' or STATUS='d' 
Ravi Kumar