SQL Help, Group by another table - mysql

select
d.DepartmentId,
d.Name,
d.GroupName,
eph.Rate * 40 * 52 * count(edh.EmployeeId) as AnnualPay
from
HumanResources.Department d,
HumanResources.EmployeePayHistory eph,
HumanResources.Employee e,
HumanResources.EmployeeDepartmentHistory edh
where
e.CurrentFlag = 'True' and
edh.DepartmentID = d.DepartmentID and
edh.EmployeeID = eph.EmployeeID and
e.EmployeeID = eph.EmployeeID
group by
d.departmentID;
The goal is to write a report to display the departmentid, name, groupname, the total annual pay for all employees who work in that department and the number of employees who work in that department.
To calculate the annual pay, multiply each of the employees’ pay rate by 40 hours for 52 weeks in the year.
Only include departments that spend more than half a million dollars on their total annual pay for all employees.
All employees should be current (use currentflag).
Sort the report by the total annual pay of employees in descending order.
The Tables are included, I can't figure out how to group by each department...Database

If I understood what you are looking for, this should work:
SELECT
d.DepartmentId,
d.Name,
d.GroupName,
SUM(eph.Rate * 40 * 52) as AnnualPay,
Count(edh.EmployeeId) as EmployeeCount
from HumanResources.Department d
JOIN HumanResources.EmployeeDepartmentHistory edh
ON edh.DepartmentID = d.DepartmentID
JOIN HumanResources.EmployeePayHistory eph
ON edh.EmployeeID = eph.EmployeeID
JOIN HumanResources.Employee e
ON e.EmployeeID = eph.EmployeeID
WHERE e.CurrentFlag = 'True'
GROUP BY d.departmentID,d.Name,d.GroupName
HAVING AnnualPay > 500000
ORDER BY AnnualPay DESC;

Please try the following...
SELECT DepartmentId AS DepartmentId,
DepartmentName AS DepartmentName,
DepartmentGroup AS DepartmentGroup,
SUM( expectedAnnualPay ) AS TotalExpectedAnnualPay,
COUNT( DepartmentId ) AS EmployeeCount
(
SELECT Department.DepartmentId AS DepartmentId,
Name AS DepartmentName,
GroupName AS DepartmentGroup
Rate *
40 *
52 AS expectedAnnualPay,
EmployeeID AS EmployeeID
FROM HumanResources.Department HRDepartment
JOIN HumanResources.EmployeeDepartmentHistory HREmployeeDepartmentHistory ON HREmployeeDepartmentHistory.DepartmentID = HRDepartment.DepartmentID
JOIN HumanResources.Employee HREmployee ON HREmployee.EmployeeID = HREmployeeDepartmentHistory.EmployeeID
JOIN HumanResources.EmployeeDepartmentHistory HREmployeeDepartmentHistory ON HREmployee.EmployeeID = HREmployeePayHistory.EmployeeID
WHERE HREmployee.CurrentFlag = 'True'
) departmentEmployee
GROUP BY DepartmentId
HAVING TotalExpectedAnnualPay > 500000
ORDER BY TotalExpectedAnnualPay DESC;
You appear to be asking for a list of the total expected annual pay amount for each department where that value is greater than $500,000.00 on the assumption that all current employees within that Department will remain with that Department for one year at the current Rate and that no Employees will be added during that time.
I approached this problem by starting with the following query (which I gave the alias of departmentEmployeeLevel)...
SELECT Department.DepartmentId AS DepartmentId,
Name AS DepartmentName,
GroupName AS DepartmentGroup
Rate *
40 *
52 AS expectedAnnualPay,
EmployeeID AS EmployeeID
FROM HumanResources.Department HRDepartment
JOIN HumanResources.EmployeeDepartmentHistory HREmployeeDepartmentHistory ON HREmployeeDepartmentHistory.DepartmentID = HRDepartment.DepartmentID
JOIN HumanResources.Employee HREmployee ON HREmployee.EmployeeID = HREmployeeDepartmentHistory.EmployeeID
JOIN HumanResources.EmployeeDepartmentHistory HREmployeeDepartmentHistory ON HREmployee.EmployeeID = HREmployeePayHistory.EmployeeID
WHERE HREmployee.CurrentFlag = 'True'
This subquery returns the DepartmentId, Department Name and GroupName of each department along with the EmployeeID of each current Employee and their computed expected annual pay.
The main query uses the results of the subquery to aggregate / group together the results by each Department and to calculate for each Department the total of the expected annual pay and the count of employees. It then uses HAVING to refine the list to only those departments whose expected annual pay cost is greater than $500,000.00 and sorts the remaining records by that field.
If you have any questions or comments, then please feel free to post a Comment accordingly.

Related

SQL select without duplicates Joined to another table by ID

I have 2 tables that I would like join where the contactid is unique and has the highest allowance.
EMPLOYEE
Employee ID
contactid
employerid
1
555444333
25435566
2
555444333
84235621
3
234232144
57353457
EMPLOYEEDETAILS
Employee ID
Annual Allowance
1
£10000
2
£1000
3
£2000
I would like to achieve below where I want to show the EmployeeID with the highest allowance for the unique contactid.
EmployeeID
contactid
Annual Allowance
1
555444333
£10000
3
234232144
£2000
I have tried the SQL code below but it's not giving me the unique contactid with the highest allowance.
SELECT EMPLOYEE.employeeid, EMPLOYEE.contactid, MAX(EMPLOYEEDETAILS.annualallowance)
from
cxm_employee EMPLOYEE
JOIN
cxm_employeedetails EMPLOYEEDETAILS ON EMPLOYEE.employeeid = EMPLOYEEDETAILS.employeeid
group by EMPLOYEE.employeeid,EMPLOYEE.employeecontactid
Where am I going wrong?
I want to show the EmployeeID with the highest allowance for the unique contactid.
Your code does not work because it only brings the details of the current employee, letting along other employees that have the same contactid.
I think it is easier to do with window functions:
select *
from (
select e.*, d.annualallowance,
rank() over(partition by e.contactid order by d.annualallowance desc) rn
from employee e
inner join employeedetails d on d.employeeid = e.employeeid
) t
where rn = 1
rank() ranks employees having the same contact by descending annual allowance ; we can then use this information for filtering.
In pre-8.0 versions of MySQL, where window functions are not supported, an alternative uses a correlated subquery to retrieve the top allowance per contact; we can then use this information to filter the dataset :
select e.*, d.annualallowance
from employee e
inner join employeedetails d on d.employeeid = e.employeeid
where d.annualallowance = (
select max(d1.annualallowance)
from employee e1
inner join employeedetails d1 on d1.employeeid = e1.employeeid
where e1.contactid = e.contactid
)
Demo on DB Fiddle

how to calculate total business added by the employees individually

I have two tables like employees and doctorsrating.
In employees table contains list of registered employees with columns of emp_bioid and emp_name and doctorspoints emp_bioid, points, pointsname, doctor_name, createdAt of columns.
Employees will add points for doctors which will stored by the emp_bioid. My question is i want to count total records added by the each and every employees.
I have tried this query but the business count was wrong.
SELECT emp_bioid, COUNT(*) as Doctor (SELECT emp_name from employees where emp_bioid = doctorsrating.emp_bioid) as emp_name FROM doctorsrating
WHERE createdAt between '2021-03-01' AND '2021-03-24' GROUP BY emp_bioid
You can make a join and group by both columns (id and name) as below:
SELECT e.emp_bioid, e.emp_name, COUNT(*)
FROM employees e
JOIN doctorsrating dr ON e.emp_bioid = dr.emp_bioid
WHERE dr.createdAt between '2021-03-01' AND '2021-03-24' GROUP BY e.emp_bioid, e.emp_name

Averaging salary by location across two tables

There are two tables, one with the employees salary and another with the department.
table1:
employee_id name salary
--------------------------------------
01 K.Irving 30000
02 J.Polk 50000
03 S.Smith 20000
04 D.Rai 35000
table2:
employee_id name department
------------------------------------------
01 K.Irving marketing
02 J.Polk finance
03 S.Smith marketing
04 D.Rai it
I would like to find out how to find the average salary per department where it is lower than 40000
Ideally it should look like this:
avg_salary department
-----------------------------
35000 it
25000 marketing
So far I have tried to combine the two tables using the following formula, however I am having trouble putting in the conditions I wanted:
SELECT table1.employee_id
, table1.name
, table1.salary
, table2.department
FROM table1
LEFT
JOIN table2
ON table1.employee_id = table2.employee_id
AND table1.employee_name = table2.employee_name
ORDER
BY salary DESC;
The solution would be a mixture of the above and below, I was not sure how to combine the two.
SELECT AVG(salary), department
FROM table1, table2
GROUP BY department
HAVING AVG(salary) <40000
ORDER BY salary DESC;
I was not sure how to get the averages per department, when I used the code above it took an average of all salaries.
You need to GROUP BY the department and limit the results with a HAVING clause.
SELECT avg(e.salary) avg_salary,
d.department
FROM table2 d
LEFT JOIN table2 e
ON e.employee_id = d.employee_id
GROUP BY d.department
HAVING avg(e.salary) < 4000
ORDER BY e.salary DESC;
But note, that your design is bad. There should be a table for the departments, that only stores the departments, not any employees to it. Then there should be a linking table with just a user and a department ID to store which employees is in which department. There should not be the employee (or the department) name in that table.
A LEFT JOIN is unnecessary for this problem. In order for the average to be well-defined, you need to have matches between the tables. Hence:
SELECT avg(e.salary) as avg_salary,
d.department
FROM table2 d JOIN
table2 e
ON e.employee_id = d.employee_id
GROUP BY d.department
HAVING avg_salary < 4000
ORDER BY e.salary DESC;
As a convenience, you can also use the column alias in the HAVING clause.

Select maximum value from one column by second column

I have two tables:
EMPLOYEES
=====================================================
ID NAME SUPERVISOR LOCATION SALARY
-----------------------------------------------------
34 John AL 100000
17 Mike 34 NY 75000
5 Alan 34 LE 25000
10 Dave 5 NY 20000
BONUS
========================================
ID Bonus
----------------------------------------
17 5000
34 5000
10 2000
I have to write query which return a list of the highest paid employee in each location with their names, salary and salary+bonus. Ranking should be based on salary plus bonus. So I wrote this query:
select em.name as name, em.salary as salary, bo.bonus as bonus, max(em.salary+bo.bonus) as total
from employees as em
join bonus as bo on em.empid = bo.empid
group by em.location
But I'm getting wrong names and query don't return one employee without bonus (empid = 5 in employees table) which have highest salary based by location (25000 + 0 bonus).
You can either do
select
em.location,
em.name as name,
em.salary as salary,
IFNULL(bo.bonus,0)) as bonus,
max(em.salary+IFNULL(bo.bonus,0)) as total
from employees as em
left join bonus as bo on em.empid = bo.empid
group by em.location;
This query however relies on a group by behavior that is specific to MySQL and would fail in most other databases (and also in later versions of MySQL if the setting ONLY_FULL_GROUP_BY is enabled).
I would suggest a query like below instead:
select
em.location,
em.name as name,
em.salary as salary,
IFNULL(bo.bonus,0)) as bonus,
highest.total
from employees as em
left join bonus as bo on em.empid = bo.empid
join (
select
em.location,
max(em.salary+IFNULL(bo.bonus,0)) as total
from employees as em
left join bonus as bo on em.empid = bo.empid
group by em.location
) highest on em.LOCATION = highest.LOCATION and em.salary+IFNULL(bo.bonus,0) = highest.total;
Here you determine the highest salary+bonus for each location and use that result as a derived table in a join to filter out the employee with highest total for each location.
See this SQL Fiddle
Maybe try using a left join:
select em.name as name, em.salary as salary, bo.bonus as bonus, max(em.salary+bo.bonus) as total
from employees as em
left join bonus as bo on em.empid = bo.empid
group by em.location
It should be:
select
em.name as name,
em.salary as salary,
COALESCE(bo.bonus,0) as bonus,
max(em.salary + COALESCE(bo.bonus,0) ) as total
from employees as em
left join bonus as bo on em.empid = bo.empid
group by em.location
You can check it in SQLFiddle
Please try this:
select em.name as name, em.salary as salary,ISNULL(bo.bonus,0) as bonus,
max(em.salary+ISNULL(bo.bonus,0)) as total
from employees as em
left join bonus as bo on em.ID = bo.ID
group by em.name,em.salary, bo.bonus order by MAX(em.salary+ISNULL(bo.bonus,0)) Desc

I need help with a MySQL query

I have two tables - `employee` and `department`.
1. `employee` table contains column id,employee name and dept_id
2. `department` table contains column id, department name.
I need exact department name which contains
1. maximum employee and
2. no employee
Edited:
Apologizing for bad grammar, here is the example for above two questions what i need.
1. for eg: if two department contains same number of employees, i need to show both department not single by limit.
2. for eg: if more than one department contains 0 employees, i must show those departments particularly.
select department_name as `department name`,
count(*) as `number of employees`
from employee
inner join department
on employee.dept_id = department.id
group by department_name
order by count(*) desc
limit 1
i think that should do it. i've not done anything with mysql in a while.
edit: missed the second question
select department_name as `department name`,
count(*) as `number of employees`
from employee
left join department
on employee.dept_id = department.id
group by department_name
HAVING count(*) = 0
Answer to the first question:
WITH epcount(dept_id, ep_count) AS
(
SELECT dept_id, COUNT(*) AS ep_count
FROM employee
GROUP BY dept_id
)
SELECT d.name FROM epcount AS ec1 JOIN department AS d ON ec1.dept_id=d.id
WHERE NOT EXISTS
(SELECT * FROM epcount AS ec2 WHERE ec1.ep_count < ec2.ep_count)
Answer to the second question:
SELECT name FROM department AS d
WHERE NOT EXISTS
(SELECT * FROM employee AS e WHERE d.id=e.dept_id)
If I read the question right, you need:
select department_name,
count(employee.dept_id) as num_employees
from department
left join employee on employee.dept_id = department.id
group by department_name
having count(employee.dept_id) = 0 or
count(employee.dept_id) = (select count(dept_id)
from employee
group by employee.id
order by count(dept_id) desc
limit 1)
This will get you a sorted list of departments, sorted by number of employees.
SELECT `dept`.`id`, `dept`.`name`, COUNT(`employee`.`id`) as `employee_count`
FROM `dept` LEFT JOIN `employee`
ON `employee`.`dept_id` = `dept`.`id`
GROUP BY `dept`.`id`
ORDER BY `employee_count`
To get departments with no employees, add:
AND `employee_count` = 0
...before the GROUP BY.
To get the department with the most employees, add DESC LIMIT 1 to the end.
Query that shows department names with maximum employees and number of employees in it:
SELECT department.name, COUNT(employee.name) from department
INNER JOIN employee
ON employee.dept_id = department.id
GROUP BY department.name
ORDER BY COUNT(employee.name) DESC limit 1
Query that shows departments with no employees:
SELECT department.name from department
LEFT JOIN employee
ON employee.dept_id = department.id
HAVING COUNT(employee.name) = 0
GROUP BY department.name
If you need to show it in one query, paste first query, add UNION ALL and then paste second query.