Pergunta

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.

Foi útil?

Solução

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

Outras dicas

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

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top