单个查询中的多次计数(*)

时间:2014-05-08 05:36:15

标签: sql oracle oracle11g

我需要一个查询来根据某些条件(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

我想在1个查询中获取所有三个结果。我在google搜索后尝试过以下但是它无效:

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

它不起作用。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以使用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

但它会在一列中显示所有三个COUNT。要在三个不同的列中显示它,请尝试以下操作:

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 

答案 2 :(得分: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

答案 3 :(得分:0)

而不是:

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

尝试:

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