SQL查询 - 如何获取表中的计数

时间:2012-05-11 19:47:31

标签: sql

我有一个表X,其中包含名为version的列,其中包含4-5个值,例如1,2,3,4,5

如果列值为1或3,那么我很好,否则就是错误

问题

什么是查询,以便我想要像这样的输出

总值数量|总好,即值为(1,3)|总失败,但值不在(1,3)

有人可以帮我查询

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

select count(*) as TotalValues
  , (select count(*) from test where id in(1, 3)) as TotalGood
  , (select count(*) from test where id not in (1, 3)) as TotalFailed
from test

SQL Fiddle DEMO

根据您的评论,如果您需要这个百分比,您可以使用它:

SELECT TotalValues
  , TotalGood
  , TotalFailed
  , Cast(TotalGood as decimal(10, 2))/Cast(TotalValues as decimal(10, 2)) as PercentGood
FROM 
(
  select count(*) as TotalValues
    , (select count(*) from test where id in(1, 3)) as TotalGood
    , (select count(*) from test where id not in (1, 3)) as TotalFailed
  from test
) x