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;
Select count(StockExists)
From [Items] where StockExists='T'
but it is always returning 1. What is the right way to do it?
Edit:
Also, 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'` ?
SQL Query to Count Number of Rows: The SQL COUNT () function is used to return the number of rows in a table. It is used with the Select () statement. Syntax: SELECT COUNT (colmn_name) from table_name;
The COUNT () function returns the number of rows in a group. The first form of the COUNT () function is as follows: The COUNT (*) function returns a number of rows in a specified table or view that includes the number of duplicates and NULL values.
The COUNT (*) returns the number of rows including duplicate, non-NULL and NULL rows. The COUNT (expression) returns the number of rows that do not contain NULL values as the result of the expression.
Introduction to SQL COUNT function. The SQL COUNT function is an aggregate function that returns the number of rows returned by a query. You can use the COUNT function in the SELECT statement to get the number of employees, the number of employees in each department, the number of employees who hold a specific job, etc.
SELECT
COUNT(*) As ExistCount
FROM
dbo.Items
WHERE
StockExists='T'
So your query should work.
Result:
EXISTCOUNT
2
Demo
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' ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With