2011-05-12 126 views
0

我有一個列名狀態(INT),其中只有0和1被插入取決於邏輯,我要計數的查詢,其可以指望1多少0和有多少在有在單個查詢中如表:計數多個數據查詢的單個列

SELECT COUNT(狀態)從產品詳情......

回答

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

countOfZeros和那些..是它建立在SQL Server feauture – 2011-05-12 10:51:40

+0

countOfOnes和countOfZeros是結果列的名稱... – 2011-05-12 10:52:36

+0

我認爲我們使用結果列 – 2011-05-12 10:53:59

1

另一個變化:

select 
    count(*) countOverall, 
    sum(state) countOfOnes, 
    count(*) - sum(state) countOfZeroes 
from 
    productDetail; 
-1
select count(state) from productDetail Where state = 0 
select count(state) from productDetail Where state = 1 
+0

這是兩個陳述... OP要求單個查詢。 – 2011-05-12 10:52:01