Skip to content

Instantly share code, notes, and snippets.

@LarryBattle
Forked from dritterman/gist:5662750
Created May 28, 2013 15:47
Show Gist options
  • Save LarryBattle/5663748 to your computer and use it in GitHub Desktop.
Save LarryBattle/5663748 to your computer and use it in GitHub Desktop.
1. List employees (names) who have a bigger salary than their boss
SELECT
e.`name`
FROM
employees AS e
INNER JOIN employees AS b ON e.bossid = b.employeeid
WHERE
e.salary > b.salary
2. List employees who have the biggest salary in their departments
SELECT
employees.`name`
FROM
employees
GROUP BY
employees.departmentid
ORDER BY
employees.salary ASC
3. List departments that have less than 3 people in it
SELECT
departments.`name`
FROM
departments
LEFT JOIN employees ON employees.departmentid = departments.departmentid
GROUP BY
departments.departmentid
HAVING
COUNT(*) < 3
4. List all departments along with the number of people there (tricky - people often do an "inner join" leaving out empty departments)
SELECT
departments.`name`,
Count(employees.employeeid) as count
FROM
departments
LEFT JOIN employees ON employees.departmentid = departments.departmentid
GROUP BY
departments.departmentid
5. List employees that don't have a boss in the same department
SELECT
e.`name`
FROM
employees AS e
INNER JOIN employees AS b ON e.bossid = b.employeeid
WHERE
e.departmentid <> b.departmentid
6. List all departments along with the total salary there
SELECT
departments.`name`,
Sum(employees.salary)
FROM
departments
LEFT JOIN employees ON employees.departmentid = departments.departmentid
GROUP BY
departments.`name`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment