0

I need a single query to fetch the counts based on some condition(oracle).

select count(*) AS TOTAL_ROWS from table

select count(*) AS TOTAL_ERROR_ROWS from table where ERROR_CODE is not null

select count(*) AS TOTAL_SUCCESS_ROWS from table where ERROR_CODE is  null

I want to fetch all three results in 1 query. I have tried like below after googling but it is not working:

select
   count(*) as TotalCount,
   count(case when { where ERROR_CODE is not null} then 1 else 0 end) as QualifiedCount
from
   wli_qs_report_attribute

select count(*) as TOTAL,
    count(case when ERROR_CODE is not null then 1 else 0 end) as ExecCount,
from wli_qs_report_attribute

it doesn't work.

4 Answers 4

2

SELECT TOTAL_ROWS, TOTAL_ERROR_ROWS, TOTAL_ROWS-TOTAL_ERROR_ROWS AS TOTAL_SUCCESS_ROWS FROM ( SELECT COUNT(*) AS TOTAL_ROWS , COUNT(ERROR_CODE) AS TOTAL_ERROR_ROWS FROM table ) AS T

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

Comments

1

You can use UNION :

select count(*) AS TOTAL_ROWS from table

UNION

select count(*) AS TOTAL_ROWS from table where ERROR_CODE is not null

UNION

select count(*) AS TOTAL_ROWS from table where ERROR_CODE is  null

But it will display all three COUNTs in one column. To display it in three different columns try the following :

SELECT COUNT(*) AS TOTAL_ROWS
     , COUNT(CASE WHEN ERROR_CODE IS NOT NULL THEN * END) AS TOTAL_ERROR_ROWS
     , COUNT(CASE WHEN ERROR_CODE IS NULL THEN * END) AS TOTAL_SUCCESS_ROWS
FROM table 

Comments

1
SELECT COUNT(*) AS TOTAL_ROWS,
       SUM(CASE WHEN ERROR_CODE IS NOT NULL THEN 1 end) AS TOTAL_ERROR_ROWS,
       SUM(CASE WHEN ERROR_CODE IS NULL THEN 1 END) AS TOTAL_SUCCESS_ROWS 
FROM table

Comments

0

Instead of:

count(case when ERROR_CODE is not null then 1 else 0 end) as ExecCount

Try:

sum(case when ERROR_CODE is not null then 1 else 0 end) as ExecCount

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.