Advertisement
simonradev

T-SQL Subqueries

Sep 13th, 2017
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.82 KB | None | 0 0
  1. SELECT CurrentEmployees.DepartmentID,
  2.        MAX(CurrentEmployees.Salary) AS [Third Highest Salary]
  3.  FROM Employees AS CurrentEmployees, (SELECT CurrentEmployees.DepartmentID,
  4.                                            MAX(CurrentEmployees.Salary) AS [Second Highest Salary]
  5.                                       FROM Employees AS CurrentEmployees, (SELECT DepartmentID,
  6.                                                                                    MAX(Salary) AS [Highest Salary]
  7.                                                                              FROM Employees
  8.                                                                              GROUP BY DepartmentID) AS PreviousEmployees
  9.                                       WHERE CurrentEmployees.DepartmentID = PreviousEmployees.DepartmentID AND
  10.                                            CurrentEmployees.Salary < PreviousEmployees.[Highest Salary]
  11.                                       GROUP BY CurrentEmployees.DepartmentID) AS PreviousEmployees
  12.  WHERE CurrentEmployees.DepartmentID = PreviousEmployees.DepartmentID AND
  13.        CurrentEmployees.Salary < PreviousEmployees.[Second Highest Salary]
  14.  GROUP BY CurrentEmployees.DepartmentID
  15.  
  16. -----------------------------------------------------------------------------------------------------------------------------------
  17.  
  18. SELECT TOP(10) Employees.FirstName,
  19.        Employees.LastName,
  20.        Employees.DepartmentID
  21.  FROM Employees, (SELECT DepartmentID,
  22.                          AVG(Salary) AS [Average Salary For Department]
  23.                    FROM Employees
  24.                    GROUP BY DepartmentID) AS DepartmentsAndTheirAverageSalaries
  25.  WHERE Employees.DepartmentID = DepartmentsAndTheirAverageSalaries.DepartmentID AND
  26.        Employees.Salary > DepartmentsAndTheirAverageSalaries.[Average Salary For Department]
  27.  ORDER BY Employees.DepartmentID
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement