SQL Query to fetch emloyee name, salary where employee name is provided - mysql

For an Employee table with columns EmpId, Name and Salary Table with columns Id, EmpId, Salary, where EmpId of salary table is Foreign Key of Employee Table.
Is it possible to write a SQL query so that the result contains each employee's name and the salary of all employees provided by a employee name?
Sample Data
Employee Table
EmpId Name
1 Alice
2 Bob
3 Charlie
4 Doug
Salary Table
Sample Data
Id EmpId Salary
1 1 1000
2 2 2000
3 3 3000
4 4 4000
Query I tried, but could not see, how I can write employee name say, Bob, where I want to fetch employee who have higher salary than Bob. Below query gives result with salary perspective, but how to fetch by employee name?
--Updated with Order By Clause, Thanks #Strawberry
SELECT s.salary
, e.empname
FROM
test.employee as e, test.salary as s
WHERE s.empid = e.empid AND s.salary > 2000
ORDER BY s.Salary DESC
LIMIT 3;

Here is the query with which you can fetch the salary of Bob:
SELECT Salary
FROM salary
WHERE EmpId = 2;
Now you want to fetch all names and salaries of employees who have higher salary than what you fount with the query above. Therefore you will use the above query as a nested one in WHERE. Here you go:
SELECT employee.EmpId, employee.Name, salary.Salary
FROM employee
JOIN salary ON employee.EmpId = salary.EmpId
WHERE salary > (
SELECT Salary
FROM salary
WHERE EmpId = 2
);
Edit - below in the comments you said that you want to filter by Name, not EmpId. Therefore you probably want to filtler with WHERE Name="Bob". The problem is that usually names are not unique. Therefore you may have two people named "Bob". If that is the case, you must figure out a solution which salary to get - they may be different.
Here is an example query that will get the salary of person named "Bob" who have the highest salary among all Bobs, then filter the other employees to have higher salary than whatever is fount:
SELECT employee.EmpId, employee.Name, salary.Salary
FROM employee
JOIN salary ON employee.EmpId = salary.EmpId
WHERE salary > (
SELECT MAX(Salary)
FROM salary
WHERE EmpId IN (
SELECT EmpId
FROM employee
WHERE Name="Bob"
)
);
Eventual issue may come if there is NO person named "Bob". The above query will return an empty set. If you want to print all people instead, you can do something like this:
SELECT employee.EmpId, employee.Name, salary.Salary
FROM employee
JOIN salary ON employee.EmpId = salary.EmpId
WHERE salary > (
SELECT IF(MAX(Salary) IS NULL, 0, MAX(Salary))
FROM salary
WHERE EmpId IN (
SELECT EmpId
FROM employee
WHERE Name="Bob"
)
);
Now if there is no "Bob", it will still print all people with salaries above 0.

Related

How to find those departments whose sum of employee's salary is greater than or equal to 10,000 in SQL?

Here is the screenshot of the table and my attempt of this query
here's the query that I am running
SELECT department
FROM employees
where ( select sum(salary)
group
by department
having sum(salary) >=10000);
It returns 0 rows whereas it should return 'COE' as the sum of its employees is 14000
I think you just want this:
select department
from employees
group by department
having sum(salary) >= 10000;

I am trying to get latest month salary from salary table, where multiple entry of employeeID in salary table for each month

Employee table"
empno,
ename,
sal_id,
emp_id,
salary,
month
SALARY table:
sal_id,
emp_id,
salary,
month
I am trying to make query for getting all employee from employee table +
In salary table, there are multiple entry (may be not) of emp_id.
I want employee list with their latest salary( or last month salary)
My current query is :
SELECT * FROM emp LEFT JOIN salary ON emp.empno = salary.emp_id GROUP BY empno ORDER BY salary.sal_id DESC
But I am getting emp list with first salary, I want with latest salary.
Help me :(
Emploee table
Salary table
You are ordering by sal_id instead you might want to order by a field in salary which represents its month.
SELECT emp.empno, emp.name, (
SELECT sal
FROM salary
WHERE salary.empno = emp.empno
ORDER BY salary.sal_id DESC LIMIT 1
)
FROM emp
I have come with solution after a lot R&D and googling .
It is not possible in single query, we have to apply 2 query
SELECT * FROM emp LEFT JOIN salary ON salary.emp_id=emp.empno WHERE salary.sal_id IN ( SELECT MAX(salary.sal_id) FROM salary GROUP BY salary.emp_id ) GROUP BY salary.sal_id ORDER BY salary.sal_id DESC

How to get second highest salaried employees in mysql

I have an employee table in MySQL with below entries. I need to find all the employees having second highest salaries. In this case, it would be c and d.
id | name | salary
1 | a | 1000
2 | b | 1000
3 | c | 500
4 | d | 500
5 | e | 400
I tried running below query
SELECT name, MAX(salary) FROM employee WHERE salary < (SELECT MAX(salary) from employee);
But this query returns just c as a result. How to get both c and d in result?
I looked at bunch of similar questions posted but none of them mentioned how to get multiple rows for second highest salary.
You can esily get second highest salary from table
SELECT MAX(salary) FROM Employee WHERE Salary NOT IN ( SELECT Max(Salary) FROM Employee);
You can find the second highest salary with:
SELECT salary
FROM employee
GROUP BY salary
ORDER BY salary DESC
LIMIT 1, 1
Then either feed the result of that to another query in the same transaction:
SELECT *
FROM employee
WHERE salary = ?
Or do it as a subquery:
SELECT *
FROM employee
WHERE salary = (
SELECT salary
FROM employee
GROUP BY salary
ORDER BY salary DESC
LIMIT 1, 1
)
In case you want migrate to MSSQL Server :).
SELECT * FROM (
SELECT MAX(salary) T,RANK() OVER (ORDER BY SALARY DESC) AS RankBySalary FROM Employees
GROUP BY SALARY ) TB
WHERE RankBySalary = 3
Or much better:
SELECT * FROM
(
SELECT ID,NAME,SALARY,DENSE_RANK() OVER (ORDER BY SALARY DESC) AS RankBySalary FROM employee
)
TB WHERE RankBySalary = 2
SELECT *
FROM employee one1
WHERE ( N ) = (
SELECT COUNT( one2.salary )
FROM employee one2
WHERE one2.salary > one1.salary
)
Note : N means Nth highest salary
Demo
First find the second highest salary amount then select the rows having that salary.
Query
select * from Employees
where Salary = (
select min(t.salary) from (
select salary
from Employees
group by salary
order by salary desc limit 2
)t
);
SQL Fiddle demo
I suggest that you must first select the 2nd highest salary first and then use the derived table with JOIN on original table. like this:
SELECT
original_record.*
FROM
salary_record AS original_record
JOIN
(SELECT
distinct salary
FROM
salary_record
ORDER BY 1
LIMIT 1,1
) AS derived_record
ON
original_record.salary = derived_record.salary
PS: I have renamed your employee table as salary_record table
Also have a look at Varoon Sahgal's article on Nth highest salary, here: http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/ . The comments-section of this article as well as the article itself has some optimized examples.
select name,max(salary) from employee x where (n-1)=(select count(distinct salary)from employee y where x.salary<y.salary);
Nth max salary
-- IF THIS TABLE EXISTS, DROP IT
DROP TABLE E2;
-- THE FOLLOWING CTE ARRANGES SALARIES IN DECENDING ORDER
WITH copytable(Salary) AS
(
SELECT Emp1.Salary
FROM Employees AS Emp1, Employees AS Emp2
WHERE Emp1.Salary > Emp2.salary
GROUP BY Emp1.Salary
)
-- COPY THE CTE IN A TABLE
SELECT * INTO E2 FROM copytable
-- GIVES THE RANK TO THE SALARY IN DECENDING ORDER
ALTER TABLE E2
ADD RankOfSalary INT IDENTITY(1, 1)
-- TO GET THE LOWEST RANK WHICH WILL BE THE HIGHEST SALARY
DECLARE #rankOfSalary int;
SELECT #rankOfSalary = COUNT(Salary) from E2;
-- SELECTING THE SECOND LARGEST SALARY
DECLARE #SelectSalary INT
SELECT #SelectSalary = Salary from E2 where RankOfSalary = #rankOfSalary - 1;
THIS IS HOW YOU DO IT WITHOUT USING max(), order by, top in sql server
to select second largest salary of employees without using max(), order by, top in sql server
JUST WANTED TO POST THIS :p
You can get it by this:
2nd Largest Salary:
SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees))
3rd Largest Salary:
SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees)))
Helpful links:
http://www.mysqltutorial.org/select-nth-highest-record-database-table-using-mysql.aspx
http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/
http://www.coderanch.com/t/530503/JDBC/databases/select-Nth-highest-salary-table
try this TO GET BOTH c AND d
SELECT
name, salary
FROM
employee
WHERE salary = (
SELECT salary
FROM employee
GROUP BY salary
ORDER BY salary DESC
LIMIT 1,1
);

My sql Group By case for getting highest paid employee in specific year

there is two table
1 Employee
2 salary
Employee : eId, ename, salaryId
Salary : salaryId, eId, salary, date
salary table contains monthly record of employee salary,
like:
eId date salary
1 2015-jan-01 10000
1 2015-feb-01 10000
1 2015-mar-01 10000
1 2014-jan-01 10000
1 2014-feb-01 10000
1 2014-mar-01 10000
2 2015-jan-01 10000
2 2015-feb-01 10000
2 2015-mar-01 10000
2 2014-jan-01 10000
2 2014-feb-01 10000
2 2014-mar-01 20000
so the query is to give me highest paid employee in specific year for ex: 2014
so here using group by with date and sum of salary output is :
empid - empname - sum(salary)
2 - xyz - 40000
Try it with something like this ... i just took a glance to point you toward right direction, this query might need some fixing
Select TOP 1 emp.eid, emp.ename, sal.salary
from Employee emp
join Salary sal on emp.salaryID = sal.salaryID
where DATEPART(yy,sal.date) = 2014
order by sal.salary desc
Good luck
Something like this could work
with salaries as (
select to_char(date,'yyyy') y, eld, sum(salary) s_sal
from salary
group by to_char(date,'yyyy'), eld)
select eld
from salaries s
where s_sal = (select max(s_sal) from salaries where y=s.y)
and s.y='2014';
But you didn't specify DB, so there is Oracle syntax.
And I didn't join with Employee table, but believe it isn't hard to add it.
If the requirement is to get the list of highest paid employee in each year then this can be achieved by a "Ranking" logic.
Something like this:
SELECT
Year(SalaryMonthDate) AS [Payroll Year],
EID,
Sum(Amout) AS [Annual Salary],
RANK() OVER(PARTITION BY Year(SalaryMonthDate) ORDER BY Sum(Amout) DESC) [Rank]
FROM tblSalary
GROUP BY Year(SalaryMonthDate), EID
Hope this helps.
MySQL Code,
SELECT Top 1 E.ename EmployeeName,
MAX(salary) AS EmployeeSalary
FROM Employee E
INNER JOIN Salary S
ON E.salaryID = S.salaryID
WHERE YEAR(S.Date) = 2014
GROUP BY
E.eId,
E.ename
#highest paid emp in specific year
SELECT e.empId,e.empName,SUM(s.salary),s.salDate
FROM emp e INNER JOIN salary s ON e.empId = s.empId
WHERE YEAR(s.salDate)=2009 GROUP BY s.empId ORDER BY SUM(s.salary) DESC LIMIT 1;

Find the dept that is being paid the max salary

I'm a student and am working on a MySql assignment given to us for the holidays.
I have a table that looks something like this :
name dept salary
A Sales 100
B Marketing 200
C Sales 800
(Sorry I'm new to stackexchange so I don't know how to display a table.)
The question for the query is : find the dept that is being paid the max salary.
I entered the following query :
SELECT dept
, SUM(salary)
FROM emp
GROUP BY dept
HAVING MAX(SUM(salary));
But I am getting the following error:
'Invalid use of group function error'.
In case salary sum is unique, you can calculate sum for each dept then order records in descending order by aggregated salary and fetch the first record (with the greatest salary):
select dept
, sum(salary) as salary
from tbl
group by dept
order by salary desc
limit 1
In case salary sum can be the same for multiple depts you can calculate salary sum for each dept , then find maximum salary sum the same way as explained above and using a having clause validate if salary sum for each group is equal to the maximum salary sum:
select dept
from tbl
group by dept
having sum(salary) = ( select sum(salary) as salary
from tbl
group by dept
order by salary desc
limit 1)