Wednesday, October 19, 2011

SQL: COUNT

Faisal and Shafeen working with cell phone


I got this info from http://www.techbookreport.com/index.html
We can aggregate records so that we can calculate sums, averages, counts and so on.
One of the simplest operations to perform is a simple count of records in a table. To do this we need only add to the simplest of SELECT queries. First we create an alias to store the result, and then we use the COUNT command to count a given field - in our case EmpNo:

SELECT DISTINCT Count(User.EmpNo) AS Total
FROM User;

What if we want something a bit more complex, say a count of employees in each department. Here we want to group like records together based on a given field, in our case Dept. SQL provides the GROUP BY clause precisely for this task. The query then looks as follows:

SELECT Count(User.EmpNo) AS Total, User.Dept
FROM User
GROUP BY User.Dept;

Which generates the following table:

TotalDept
2Development
2Finance
3Marketing

No comments: