7

我有下表:

项目:

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. 正确的方法是什么?

编辑:

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

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

3 回答 3

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

所以你的查询应该有效。

结果:

EXISTCOUNT
    2

演示

更新

如何执行另一个这样的 Count 操作并将它们添加到一行中,例如 Select count(StockExists) From [Items] where StockExists='T' 和 Select count(Type) From [Items] where Type='Cellphone' ?

您可以SUM使用CASE

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

演示

于 2013-02-07T13:08:38.167 回答
1

选择 Sum(Case when field = 'this' then 1 else 0 end) as Total from YourTable

于 2015-04-17T14:16:08.800 回答
0

当使用 CASE WHEN 时,在 ELSE 情况下使用 NULL 比使用 0 更好,如下所示

 SELECT 
      ExistCount = SUM(CASE WHEN StockExists='T' THEN 1 ELSE NULL END) ,
      TotalCount = COUNT(ID) 
    FROM 
        dbo.Items
于 2020-02-05T13:11:28.630 回答