I am trying to insert into
a table, 5 values from other 2 tables, but when I
try to insert them, Oracle sends me a message that I am violating the unique key restriction, what I do not understand why I have this problem if I am using the distinct
clause in the select.
Thanks
My query:
x
insert into grados_salariales (Department_id,
Department_name,Sumatoria,Sal_minimo,Sal_maximo)
Select distinct departments.department_id,
departments.department_name,
sum(employees.salary),min(employees.salary),
max(employees.salary)
from employees,departments
group by salary,department_name,
departments.department_id;
This is the table that already exist and the unique key statement
create table
grados_salariales(
Department_id number,
Department_name varchar(50),
Sumatoria number,
Sal_minimo number,
Sal_maximo number);
Alter table grados_salariales
add constraint Department_id_pk
primary key ( Department_id);
I would expect inserting the department_id
without problems.
Advertisement
Answer
This is your query:
select distinct d.department_id, d.department_name,
sum(e.salary), min(e.salary),
max(e.salary)
from employees e join
departments d
on e.department_id = d.department_id
group by e.salary, d.epartment_name, d.department_id;
The problem is the salary
in the group by
. If you want one row per department, then you can do:
select d.department_id, d.department_name,
sum(e.salary), min(e.salary),
max(e.salary)
from employees e join
departments d
on e.department_id = d.department_id
group by d.department_name, d.department_id;
Notes:
- Never use commas in the
FROM
clause. - Always use proper, explicit, standard
JOIN
syntax. - Use table aliases so your queries are easier to write and read.
SELECT DISTINCT
is almost never appropriate withGROUP BY
.