0

I have an employee table, dependent table

employee table

  • empid
  • empname
  • status(working,retired,deceased,terminated)

Dependent

  • id
  • empid
  • name
  • relationtoemp
  • age....etc

Now, i want to query to get the count of total employees, count of total employees in each status(working,retired..), count of all dependants for all employees

Any help?

ASD
  • 4,747
  • 10
  • 36
  • 56

3 Answers3

0

The keyword you're looking for is "Count"

For exemple : 'SELECT COUNT(empid) FROM employee WHERE status = working'

This will give you the number of employees which status is "working"

HReynaud
  • 54
  • 1
  • 9
  • YEs i got that with single table .but i need to include dependants table also and get the count in single query – ASD May 12 '17 at 11:02
0

This will give you counts grouped by status

SELECT COUNT(emp.empid)  as counts, status
FROM employee emp join employee2 emp2 on emp.empid = emp2.empid
group by status
jimmy8ball
  • 746
  • 5
  • 15
  • YEs i got that with single table .but i need to include dependants table also and get the count in single query – ASD May 12 '17 at 11:06
  • this will be only counting empid where there is a match to your dependent table, so this will do what you need – jimmy8ball May 12 '17 at 11:07
  • if there are no dependent records in table2 they will be removed form the count by the inner join – jimmy8ball May 12 '17 at 11:08
0

You can try Prepared Statements like this:

set @sql = (
    select group_concat(distinct 
        concat(
            "sum(case when `status`='", e.status, "' then 1 end) as `", e.status, "`"
        )
    ) 
    from employee e
);

set @sql = concat("select count(e.empid) total_emp, (select count(*) from dependent) total_dep , ", @sql, " from employee e");

prepare stmt from @sql;

execute stmt;

The first part will dynamically generate columns for each employee status, and with a subselect you can count the total of dependents.

Filipe Martins
  • 608
  • 10
  • 23