Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'` ? 
like image 313
Victor Mukherjee Avatar asked Feb 07 '13 13:02

Victor Mukherjee


People also ask

How to count number of rows in a table in SQL?

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;

What is the count () function in MySQL?

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.

What is the difference between count and count (*) in SQL?

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.

How do I get the Count of an employee in SQL?

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.


1 Answers

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

like image 172
Tim Schmelter Avatar answered Sep 19 '22 21:09

Tim Schmelter