I have the following table:
我有下表:
Items:
项目:
ID Type StockExists
01 Cellphone T
02 Cellphone F
03 Apparrel T
I want to count the number of items
with existing stocks, i.e., the number of rows with StockExists='T'
. I was performing the query as;
我想计算现有股票的项目数,即StockExists ='T'的行数。我正在执行查询;
Select count(StockExists)
From [Items] where StockExists='T'
but it is always returning 1. What is the right way to do it?
但它总是回归1.做正确的方法是什么?
Edit:
编辑:
Also, how to perform another such Count operation and add them together in one row, for example,
另外,如何执行另一个这样的Count操作并将它们放在一行中,例如,
Select count(StockExists)
From [Items] where StockExists='T'` and `Select count(Type)
From [Items] where Type='Cellphone'` ?
2 个解决方案
#1
9
SELECT
COUNT(*) As ExistCount
FROM
dbo.Items
WHERE
StockExists='T'
So your query should work.
所以你的查询应该有效。
Result:
结果:
EXISTCOUNT
2
演示
Update
更新
How to perform another such Count operation and add them together in one row, for example, Select count(StockExists) From [Items] where StockExists='T' and Select count(Type) From [Items] where Type='Cellphone' ?
如何执行另一个这样的Count操作并将它们一起添加到一行,例如,选择计数(StockExists)来自[Items]其中StockExists ='T'和Select count(Type)来自[Items]其中Type ='Cellphone'?
You can use SUM
with CASE
:
您可以将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
Result:
结果:
EXISTCOUNT CELLPHONECOUNT
2 2
演示
#2
1
Select Sum(Case when field = 'this' then 1 else 0 end) as Total from YourTable
从YourTable中选择Sum(Field ='this'然后1,0结束时为Case)
#1
9
SELECT
COUNT(*) As ExistCount
FROM
dbo.Items
WHERE
StockExists='T'
So your query should work.
所以你的查询应该有效。
Result:
结果:
EXISTCOUNT
2
演示
Update
更新
How to perform another such Count operation and add them together in one row, for example, Select count(StockExists) From [Items] where StockExists='T' and Select count(Type) From [Items] where Type='Cellphone' ?
如何执行另一个这样的Count操作并将它们一起添加到一行,例如,选择计数(StockExists)来自[Items]其中StockExists ='T'和Select count(Type)来自[Items]其中Type ='Cellphone'?
You can use SUM
with CASE
:
您可以将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
Result:
结果:
EXISTCOUNT CELLPHONECOUNT
2 2
演示
#2
1
Select Sum(Case when field = 'this' then 1 else 0 end) as Total from YourTable
从YourTable中选择Sum(Field ='this'然后1,0结束时为Case)