如何计算mssql中具有特定数据的行数

Vic*_*jee 7 sql-server count

我有下表:

项目:

ID     Type     StockExists  
01     Cellphone   T
02     Cellphone   F
03     Apparrel    T
Run Code Online (Sandbox Code Playgroud)

我想count the number of items用现有股票,即行数StockExists='T'.我正在执行查询;

Select count(StockExists) 
From [Items] where StockExists='T'
Run Code Online (Sandbox Code Playgroud)

但它总是回归1.这样做的正确方法是什么?

编辑:

另外,如何执行另一个这样的Count操作并将它们放在一行中,例如,

Select count(StockExists) 
From [Items] where StockExists='T'` and `Select count(Type) 
From [Items] where Type='Cellphone'` ? 
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 9

SELECT 
    COUNT(*) As ExistCount 
FROM 
    dbo.Items
WHERE
    StockExists='T'
Run Code Online (Sandbox Code Playgroud)

所以你的查询应该有效.

结果:

EXISTCOUNT
    2
Run Code Online (Sandbox Code Playgroud)

演示

更新

如何执行另一个这样的Count操作并将它们一起添加到一行,例如,选择计数(StockExists)来自[Items]其中StockExists ='T'和Select count(Type)来自[Items]其中Type ='Cellphone'?

你可以用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
Run Code Online (Sandbox Code Playgroud)

结果:

EXISTCOUNT    CELLPHONECOUNT
    2               2
Run Code Online (Sandbox Code Playgroud)

演示