How to count the number of rows with specific data in mssql

I have the following table:

Products:

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. number of rows with StockExists='T' . I ran the request as:

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

but he always comes back 1. What is the right way to do this?

Edit:

Also, how to perform another Count operation and add them together on the same line, for example,

 Select count(StockExists) From [Items] where StockExists='T'` and `Select count(Type) From [Items] where Type='Cellphone'` ? 
+7
source share
2 answers
 SELECT COUNT(*) As ExistCount FROM dbo.Items WHERE StockExists='T' 

So your request should work.

Result:

 EXISTCOUNT 2 

Demo

Update

How to perform another operation Count and add it together one line, for example, Select the counter (StockExists) From [Items], where StockExists = 'T' and select count (Type) from [Items], where Type = "Mobile phone"?

You can use SUM with 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 

Demo

+9
source

Select Sum (case when field = 'this' and then another 1 end 0) as Total from your table

+1
source

All Articles