2013-02-07 16 views
7

與特定的數據行數我有如下表:如何計算在MSSQL

項目:

ID  Type  StockExists 
01  Cellphone T 
02  Cellphone F 
03  Apparrel T 

我想count the number of items與現有的股票,即行與StockExists='T'數。我正在執行查詢;

Select count(StockExists) 
From [Items] where StockExists='T' 

但它總是返回1.什麼是正確的方法來做到這一點?

編輯:

此外,如何執行另一個這樣的計數操作,並加在一起他們在一排,例如,

Select count(StockExists) 
From [Items] where StockExists='T'` and `Select count(Type) 
From [Items] where Type='Cellphone'` ? 
+0

你的查詢看起來很好[DEMO](http://sqlfiddle.com/#!6/c0e44/2) – Kaf

回答

9
SELECT 
    COUNT(*) As ExistCount 
FROM 
    dbo.Items 
WHERE 
    StockExists='T' 

所以您的查詢應該工作。

結果:

EXISTCOUNT 
    2 

Demo

更新

如何執行另一個這樣的計數操作,並一起加入他們 一行,例如,SELECT COUNT(StockExists )從[Items] StockExists ='T'和Select count(Type)From [Items] where Type ='手機'?

您可以使用SUMCASE

SELECT 
    ExistCount = SUM(CASE WHEN StockExists='T' THEN 1 ELSE 0 END) , 
    CellphoneCount = SUM(CASE WHEN Type='Cellphone' THEN 1 ELSE 0 END) 
FROM 
    dbo.Items 

結果:

EXISTCOUNT CELLPHONECOUNT 
    2    2 

Demo

+0

謝謝,它現在正在工作。我能做些什麼來得到與前一個表相同的表並使用不同的標準,並將兩個計數合併到不同列中的單行中? –

+0

@TimSchemelter請參閱編輯。 –

1

SELECT SUM(CASE WHEN字段= '本',那麼1點否則爲0結束)總數爲 from YourTable