How to get depatment wise max salary as well as name of employee having it?
Here is a correct solution:
SELECT concat(e.First_name, ' ', e.Last_name) as Name, e.SALARY
FROM Employee e
WHERE salary = (SELECT MAX(SALARY) FROM Employee e2 WHERE e2.Department = e.Department);
Group by clause to get name of highest paid employee
SQL Server 2008 supports Window Functions
which help you get what you want.
WITH recordList
AS
(
SELECT dept, employeeName, salary,
DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) rn
FROM employee
)
SELECT dept, employeeName, salary
FROM recordList
WHERE rn = 1
- SQLFiddle Demo
- TSQL Ranking Function
Find max and second max salary for a employee table MySQL
You can just run 2 queries as inner queries to return 2 columns:
select
(SELECT MAX(Salary) FROM Employee) maxsalary,
(SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )) as [2nd_max_salary]
SQL Fiddle Demo
select department(s) with maximum number of employees
Just a little more verbose than the other two solutions, but it will get the job done...feel free to tweak to your convenience.
select countbydept.*
from
(
-- from EMP table, let's count number of records per dept
-- and then sort it by count (highest to lowest)
-- and take just the first value. We just care about the highest
-- count
select dept_id, count(*) as counter
from emp
group by dept_id
order by counter desc
limit 1
) as maxcount
inner join
(
-- let's repeat the exercise, but this time let's join
-- EMP and DEPT tables to get a full list of dept and
-- employe count
select
dept.id,
dept.`name`,
count(*) as numberofemployees
from dept
inner join emp on emp.dept_id = dept.id
group by dept.id, dept.`name`
) countbydept
-- combine the two queries's results by matching the employee count
on countbydept.numberofemployees = maxcount.counter
Example: http://sqlfiddle.com/#!9/7d6a2d/1
Related Topics
What's the Best Way to Capitalise the First Letter of Each Word in a String in SQL Server
Multiplying Two Columns in SQL Server
Select Multiple Columns Count One Column and Group by One Column in One Table
Joining Tables from Different Servers
Get Last Record of a Table in Postgres
Add a Column to Specific Position in Mssql Server
Simple Check for Select Query Empty Result
Query to Calculate Average of Employee Salaries Working Under Manager in SQL
Node.Js Mssql Tedius Connectionerror: Failed to Connect to Localhost:1433 - Connect Econnrefused
Find a Matching Value in Date Range and Return Value
Left Join Without Duplicate Rows from Left Table
The Network Adapter Could Not Establish the Connection in SQL Developer
How to View SQL Table Structure in Oracle SQL Developer
How to Concatenate Many Rows With Same Id in SQL
How to Retrieve Microseconds or Milliseconds from MySQL Current Time
List All Employee'S Names and Their Managers by Manager Name Using an Inner Join