计算单个列的多个数据查询

时间:2011-05-12 10:42:34

标签: asp.net sql database count

我有一个列名状态(int),其中只插入0和1,具体取决于逻辑,我想要一个计数查询,它可以计算单个查询中表中有多少0和多少1像:

从productDetail中选择Count(state)......

3 个答案:

答案 0 :(得分:3)

select
    sum(state) countOfOnes,
    sum(decode(state, 0, 1, 0)) countOfZeros 
from
    productDetail
;

select
    sum(state) countOfOnes,
    count(*) - sum(state) countOfZeros 
from
    productDetail
;

select
    state, 
    count(*) over (partition by state order by state) countOfState
from
    productDetail
;

前两个示例将返回一行,其中包含两列:

countOfOnes  countOfZeros
=========================
154          21  

第三个示例将返回两行,每列两行,每个州一行。

state        countOfState
=========================
0            21
1            154  

答案 1 :(得分:1)

另一种变体:

select 
  count(*) countOverall,
  sum(state) countOfOnes,
  count(*) - sum(state) countOfZeroes
from
  productDetail;

答案 2 :(得分:-1)

select count(state) from productDetail Where state = 0
select count(state) from productDetail Where state = 1