Sql subquery with a group by and a join on two tables - sql

So i have two tables
EMPLOYEE- Contains columns including EMPLOYEE_NAME, DEPARTMENT_ID and SALARY
DEPARTMENTS - Contains columns including DEPARTMENT_NAME, and DEPARTMENT_ID
I need to display the department name and the average slary for each department and order it by the average salaries.
I am new to DBs and am having trouble.
I try to do a subquery in the from field ( this subquery returns exactly what i need minus the department name which requires me to then join the departments table to the results) all the data in the subquery is in one table- employees. while department name is in the departments table.
here is what i tried.
SELECT D.DEPARTMENT_NAME, T.PERDEPT
FROM
(
SELECT DEPARTMENT_ID, AVG(SALARY) AS PERDEPT
FROM EMPLOYEE
GROUP BY DEPARTMENT_ID
ORDER BY PERDEPT
) AS TEST T
JOIN DEPARTMENTS
ON D.DEPARTMENT_ID=T.DEPARTMENT_ID;
This returns a
SQL command not properly terminated
on the line with the AS TEST T
any and all help is greatly appreciated
many thanks

This query should do what you ask:
select d.department_name, avg(e.salary) as avg_salary
from salary_department d
left join employee e on e.department_id = d.department_id
group by d.department_name
order by avg(e.salary)

Simply correct your table aliases as you seem to have two aliases for subquery (TEST and T) and no assignment for D. Adjust SQL with one alias for each table/query reference:
...
(
SELECT ...
) AS T
JOIN DEPARTMENTS D
With that said, you do not even need the subquery as aggregate query with JOIN should suffice, assuming DEPARTMENT_ID is unique in DEPARTMENTS table to not double count the aggregate.
SELECT D.DEPARTMENT_NAME,
AVG(E.SALARY) AS PERDEPT
FROM EMPLOYEE E
JOIN DEPARTMENTS D
ON E.DEPARTMENT_ID = D.DEPARTMENT_ID
GROUP BY E.DEPARTMENT_ID,
D.DEPARTMENT_NAME
ORDER BY AVG(SALARY)

Related

SQL in Oracle HR Schema

I have made a query in Oracle HR schema to see the following information:
The city where the department is located
The total number of employees in the department
However, the query cannot be executed correctly and said this is "not a GROUP BY expression".
Does anyone knows what's the problem is? Thanks in advance.
SELECT department_name, city, COUNT(employees.department_id)
FROM departments
JOIN employees on (departments.department_id=employees.department_id)
JOIN locations USING (location_id)
GROUP BY department_name;
You are grouping by department and want to show the department's city. You expect this to work, because each department is in exactly one city. (SQL people call this functional dependency.)
For this to work, ...
there would have to be a unique contraint on the department name or you'd have to group by department_id instead
the DBMS must detect and support functional dependency in aggregation queries
Unfortunately, Oracle doesn't support functional dependency in aggregation queries. It forces us to put every such column in the GROUP BY clause or into an aggregation function.
So either extend the GROUP BY clause:
SELECT d.department_name, l.city, COUNT(e.department_id)
FROM departments d
JOIN employees e ON e.department_id = d.department_id
JOIN locations l USING (location_id)
GROUP BY d.department_name, l.city
ORDER BY d.department_name;
or use some aggregation function as MIN or MAX on that single value.
SELECT d.department_name, MAX(l.city) AS city, COUNT(e.department_id)
FROM departments d
JOIN employees e ON e.department_id = d.department_id
JOIN locations l USING (location_id)
GROUP BY d.department_name
ORDER BY d.department_name;
What I prefer though, is to aggregate first and only then join. You want to join the departments with their employee count, so do just that:
SELECT d.department_name, l.city, COALESCE(e.cnt, 0) AS employee_count
FROM departments d
JOIN locations l USING (location_id)
LEFT JOIN
(
SELECT department_id, COUNT(*) as cnt
FROM employees
GROUP BY department_id
) e ON e.department_id = d.department_id
ORDER BY d.department_name;
The problem is you have both aggregated and non-aggregated column (in your case city in the select list.
As I don't know the structure of location table and considering a department have only one location defined you can use max(city),
SELECT department_name, max(city) city, COUNT(employees.department_id) no_of_employees
FROM departments
JOIN employees on (departments.department_id=employees.department_id)
JOIN locations USING (location_id)
GROUP BY department_name;
As excellently explained by Thorsten, you could also group the data using OVER and PARTITION BY function which would eliminate the use of GROUP BY function.
SELECT d.department_name, l.city, COUNT(e.department_id) OVER (PARTITION BY e.department_id) as emp_count
FROM departments d
JOIN employees e ON e.department_id = d.department_id
JOIN locations l USING (location_id)
ORDER BY d.department_name;

SQL: Unable to SELECT joined column

I've written an SQL statement to display the department_id, job_id and of employees with the lowest salary, but one of the conditions required me to exclude departments with the names 'IT' and 'SALES', which were only accessible from another table departments. As such I joined the two tables using the shared column department_id and managed to filter the results as needed however, I am unable to select the department_id to display alongside the job_id and salaries. This is what I've managed so far:
SELECT EMPLOYEES.DEPARTMENT_ID JOB_ID, MIN(SALARY)
FROM EMPLOYEES JOIN DEPARTMENTS
ON DEPARTMENTS.DEPARTMENT_ID = EMPLOYEES.DEPARTMENT_ID
WHERE JOB_ID NOT LIKE '%REP'
AND DEPARTMENTS.DEPARTMENT_NAME NOT IN ('IT','SALES')
GROUP BY EMPLOYEES.DEPARTMENT_ID
HAVING MIN(SALARY) >= 6000 AND MIN(SALARY) <= 18000;
First, table aliases make the query much easier to write and read:
SELECT e.DEPARTMENT_ID, e.JOB_ID, MIN(e.SALARY)
FROM EMPLOYEES e JOIN
DEPARTMENTS d
ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
WHERE e.JOB_ID NOT LIKE '%REP' AND d.DEPARTMENT_NAME NOT IN ('IT',' SALES')
GROUP BY e.DEPARTMENT_ID, e.JOB_ID
HAVING MIN(e.SALARY) >= 6000 AND MIN(e.SALARY) <= 18000;
You need all non-aggregated columns in the GROUP BY.
Comma is missing in your query after department id in SELECT - so it considers Job ID as Alias for department ID and displayed as Job ID in query result. But again you don't have Job ID in GROUP BY Clause and need to add that in group by or have to use any aggregate function
SELECT **EMPLOYEES.DEPARTMENT_ID, JOB_ID,** MIN(SALARY)
FROM EMPLOYEES JOIN DEPARTMENTS ON DEPARTMENTS.DEPARTMENT_ID=EMPLOYEES.DEPARTMENT_ID
WHERE JOB_ID NOT LIKE '%REP' AND DEPARTMENTS.DEPARTMENT_NAME NOT IN('IT','SALES')
GROUP BY EMPLOYEES.DEPARTMENT_ID,JOB_ID
HAVING MIN(SALARY) >= 6000 AND MIN(SALARY) <= 18000;

Subquery using 3 Tables SQL

I'm trying to display the last name of the lowest paid employees from each city. The city column falls under a table titled LOCATIONS while employee information(salary, last name) falls under EMPLOYEES. Both of these tables are related share no common table, so I have to rely on a third table, DEPARTMENTS to connect the two as DEPARTMENTS contains a department_id that it shares with EMPLOYEES as well as a LOCATION_ID that it shares with LOCATIONS. This is what I have so far, but I'm having trouble with this as I've mostly worked with only two tables in the past.
SELECT LAST_NAME
FROM EMPLOYEES
WHERE (DEPARTMENT_ID) IN
(SELECT DEPARTMENT_ID
FROM DEPARTMENTS
WHERE LOCATION_ID IN
(SELECT LOCATION_ID
FROM LOCATIONS
GROUP BY CITY
HAVING MIN(SALARY)));
This seems to be an assignment in an intro course in SQL. So let's assume you can't use analytic functions, match_recognize clause, etc. Just joins and aggregates.
In the subquery in the WHERE clause below, we compute the min salary for each city. We need to join all three tables for this. Then in the overall query we join the three tables again, and we use the subquery for an IN condition (a semi-join). The overall query looks like this:
select e.last_name
from employees e join departments d
on e.department_id = d.department_id
join locations l
on d.location_id = l.location_id
where ( e.salary, l.city ) in
(
select min(salary), city
from employees e join departments d
on e.department_id = d.department_id
join locations l
on d.location_id = l.location_id
group by city
)
;
You should separate out the concept of table joins from WHERE clauses.
Use WHERE for filtering data, use JOIN for connecting data together.
I think this is what you are wanting. By the way, lose the ALL CAPS if you can.
SELECT
LAST_NAME
FROM
EMPLOYEES
INNER JOIN (
SELECT
DEPARTMENTS.DEPARTMENT_ID,
CITY,
MIN(SALARY) AS LOWEST_SALARY
FROM
EMPLOYEES
INNER JOIN DEPARTMENTS ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID
INNER JOIN LOCATIONS ON DEPARTMENTS.LOCATION_ID = LOCATIONS.LOCATION_ID
GROUP BY
DEPARTMENTS.DEPARTMENT_ID,
LOCATIONS.CITY
) AS MINIMUM_SALARIES
ON EMPLOYEES.DEPARTMENT_ID = MINIMUM_SALARIES.DEPARTMENT_ID
AND EMPLOYEES.SALARY = MINIMUM_SALARIES.LOWEST_SALARY
First of all join the tables, so you see city and employee in one row. If we group by city we get the minimum salary per city.
with city_employees as
(
select l.city, e.*
from locations l
join departments d using (location_id)
join employees e using (department_id)
)
select last_name
from city_employees
where (city, salary) in
(
select city, min(salary)
from city_employees
group by l.city
);
It is easier to achieve the same, however, with window functions (min over or rank over here).
select last_name
from
(
select
e.last_name,
e.salary,
min(e.salary) over (partition by l.city) as min_salary
from locations l
join departments d using (location_id)
join employees e using (department_id)
)
where salary = min_salary;

Order by subquery

I have the following oracle SQL code, but I can't understand what is the purpose of ordering by a subquery. Anyone can explain it clearly to me ?
SELECT employee_id, last_name
FROM employees e
ORDER BY (
SELECT department_name
FROM departments d
WHERE e.department_id = d.department_id
);
The ordering is done by results from other table. In this case the query returns only results from employees table, but the ordering is done by department_name, which is stored in departments table.
You could achieve identical result by using join, selecting only values from employees table, and ordering by department_name from departments table:
SELECT e.employee_id, e.last_name
FROM employees e INNER JOIN departments d
ON e.department_id = d.department_id
ORDER BY d.department_name
This query is valid if employee must always have a department. If there can be employees without departments then you should use LEFT join instead.
The clear intention of that query is employee_id and last_name from employees should be order by department_name from departments.
Okay, you don't subquery then go for join
select e.employee_id,e.last_name from employees e join departments d on
e.department_id = d.department_id order by d.department_name;

Join query in oracle 10g

I have written this query to display the last name, department number, and department name from all employees who work in toronto.
select last_name, job_id, department_id, department_name
from employees e
join departments d on d.department_id=e.department_id
join locations l on d.location_id=l.location_id and l.city='Toronto';
I am getting this error
ORA-00918: column ambiguously defined
When a column exists on both tables participating in a join you need to prefix the column name with an alias to specify which column you would like. In your join the department_id is shared by both tables, you can specify which column you would like using d.department_id in the selected columns list.
select
last_name,
job_id,
d.department_id, --specify which table you want this ambiguous column from
department_name
from employees e
join departments d
on d.department_id=e.department_id
join locations l on
d.location_id=l.location_id and l.city='Toronto';
use alias name to select the column from any particular table. For example, simply writing department_id will raise error, since it is available on multiple tables and it raise ambiguity error
So, better solution is select column with their alias name like
select e.last_name, e.job_id, e.department_id, d.department_name
from employees e
join departments d on d.department_id=e.department_id
join locations l on d.location_id=l.location_id and l.city='Toronto';
change the first line to:
select e.last_name, e.job_id, e.department_id, d.department_name
Try this:
select last_name, job_id, department_id, department_name
from employees
join departments using(department_id)
join locations using(location_id) where city='Toronto';